2016-09-26 81 views
0

我想創建一個組件,將打印輸出文本到屏幕上,這是我正在工作。反應 - _this2.SetState不是一個函數

class SearchBar extends Component { 
    constructor(props) { 
    super(props); 

    this.state = { term: '' }; 
    } 

    render() { 
    return (
     <div className="search-bar"> 
     <input value={this.state.term} onChange={event => this.SetState(event.target.value)} /> 
     The value of input is: {this.state.term} 
     </div> 
    ); 
    } 
} 

但是我一直在Chrome控制檯得到一個錯誤:

bundle.js:19818 Uncaught TypeError: _this2.SetState is not a function 

任何想法?

感謝

+0

的可能的複製[無法訪問陣營實例(本)事件處理程序內(http://stackoverflow.com/questions/29577977/unable-to-access-react- instance-this-inside-event-handler) – vijayst

回答

4

試試這個:

class SearchBar extends Component { 
 
    constructor(props) { 
 
    super(props); 
 
    this.state = { term: '' }; 
 
    this.setInputState = this.setInputState.bind(this); 
 
    } 
 
    
 
    setInputState(event) { 
 
    this.setState({ term: event.target.value }); 
 
    } 
 

 
    render() { 
 
    return (
 
     <div className="search-bar"> 
 
     <input value={this.state.term} onChange={this.setInputState} /> 
 
     The value of input is: {this.state.term} 
 
     </div> 
 
    ); 
 
    } 
 
}

1

我認爲你需要綁定你的這個,試試這個(沒有雙關語意)。

render() { 
    return (
     <div className="search-bar"> 
     <input value={this.state.term} onChange={event => this.setState.bind(this, event.target.value)} /> 
     The value of input is: {this.state.term} 
     </div> 
    ); 
    } 
+2

另外,它不應該是'setState'嗎?注意上限 – Li357

+0

是的,這也是一個問題,我只是複製並粘貼了他所擁有的。 –

1

您必須將{event => this.SetState(event.target.value)}函數綁定到組件this。問題是你的onChange功能不運行的組件此背景下

代碼應該是這個樣子

const onChange = (event) => { this.setState({term:event.target.value}) } 

<input value={this.state.term} onChange={onChange.bind(this) /> 
0

我相信你必須指定在該州發生了什麼變化:

this.SetState({ term: event.target.value }) 

代替

this.SetState(event.target.value) 
相關問題