目前收到此错误:
Uncaught TypeError: Cannot read property 'value' of null
我在下面的渲染函数中调用它:
<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData}/>
我也尝试过在这里打电话
componentWillMount: function(){ var name = document.getElementById('name').value; },
如何获取输入文本字段的ID并读取该值并确保其不为null?
我认为在尝试读取元素后DOM正在加载,因此为什么它为null
您需要在componentDidMount生命周期中具有函数,因为这是加载DOM时调用的函数。
componentDidMount
利用refs访问DOM元素
refs
<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/> componentDidMount: function(){ var name = React.findDOMNode(this.refs.cpDev1).value; this.someOtherFunction(name); }