2016-12-05 125 views
4

的特性“状态,”我有一个输入和一个按钮无法读取空

<input className="form-control" value={this.state.sentence} onChange={this.onChange}/> 
<button type="button" onClick={this.handleSentence}></button> 

我在构造函数中绑定两种功能。

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); 
    } 
+0

这是空的,所以我想你没有绑定功能组件范围或你做错了。粘贴整个组件代码请 –

+0

@PiotrSołtysiak我做了添加构造函数 –

回答

4

它应该是这样的:

<input className="form-control" value={this.state.sentence} onChange={this.onChange}/> 
<button type="button" onClick={this.onClick}></button> 

您绑定handleSentence方法到this.onClick。那是错误的。

+0

aha,谢谢,这让我发疯:D –

5

最佳做法是在绑定时保持函数名称相同。它避免了不必要的混淆,就像你的情况一样。你用不同的名字完成了handleSentence函数的绑定,但仍然用相同的名字调用它,所以在你的情况下函数被调用,但由于它被一个不同的名字绑定,所以它没有引用正确的上下文,其中状态是当下。

class SentenceForm extends Component { 
    constructor(props) { 
     super(props) 
     this.state = { 
      sentence: '', 
      splitedSentenceArray:[] 
     } 
     this.onChange = this.onChange.bind(this); 
     this.handleSentence = this.handleSentence.bind(this); 
    }