我有一个输入和一个按钮
<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.handleSentence}></button>
我已在构造函数中绑定(bind)了这两个函数。
onChange(e) {this.setState({sentence: e.target.value});}
handleSentence(e) {console.log('string -->',this.state.sentence)}
在handleSentence函数上,log
返回Cannot read property 'state' of null
。
但是在render(let{sentence}=this.state)
中返回正确的值,而且我也看到了我在输入中键入的内容
这是构造函数:
class SentenceForm extends Component {
constructor(props) {
super(props)
this.state = {
sentence: '',
splitedSentenceArray:[]
}
this.onChange = this.onChange.bind(this);
this.onClick = this.handleSentence.bind(this);
}
最佳答案
它应该看起来像这样:
<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.onClick}></button>
您将 handleSentence
方法绑定(bind)到 this.onClick
。那是错误的。
关于reactjs - 无法读取 null 的属性 'state',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40979468/