2016-12-05 124 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); 
    }