Reactjs 无法读取属性';州';空的
我有一个输入和一个按钮Reactjs 无法读取属性';州';空的,reactjs,jsx,Reactjs,Jsx,我有一个输入和一个按钮 <input className="form-control" value={this.state.sentence} onChange={this.onChange}/> <button type="button" onClick={this.handleSentence}></button> 在handleEntence函数上,log返回无法读取null的属性“state” 但是在render中(让{station}=this.s
<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.handleSentence}></button>
在handleEntence函数上,log
返回无法读取null的属性“state”
但是在render中(让{station}=this.state)
返回正确的值,并且我可以看到我在输入中键入的内容
这是构造函数:
应该是这样的:
<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.onClick}></button>
您将
handleEntence
方法绑定到this.onClick
。这是错误的。最好的做法是在绑定时保持函数名不变。它避免了不必要的混乱,就像你的情况一样。您已使用不同的名称绑定了handleEntence
函数,但仍使用相同的名称调用它,因此在您的案例中,函数正在被调用,但由于它是使用不同的名称绑定的,因此它没有引用正确的上下文,其中存在状态
class SentenceForm extends Component {
constructor(props) {
super(props)
this.state = {
sentence: '',
splitedSentenceArray:[]
}
this.onChange = this.onChange.bind(this);
this.handleSentence = this.handleSentence.bind(this);
}
这是空的,所以我认为您并没有将函数绑定到组件范围,或者您做得不对。粘贴整个组件代码please@PiotrSołtysiak我确实添加了构造器哈,谢谢,它让我发疯:D
<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.onClick}></button>
class SentenceForm extends Component {
constructor(props) {
super(props)
this.state = {
sentence: '',
splitedSentenceArray:[]
}
this.onChange = this.onChange.bind(this);
this.handleSentence = this.handleSentence.bind(this);
}