2017-10-04 56 views
0

使用Udemy課程學習反應。在嘗試輸出狀態值時進入錯誤狀態:Uncaught TypeError:無法讀取未定義的屬性'setState' - 尚未使用ES6

import React, {Component} from 'react'; 

// Create a new component and make this component produce some HTML 

class SearchBar extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      term: '' 
     }; 
    }; 

    render() { 
     return (
      <div> 
       <input onChange={this.onInputChange}></input> 
       Value of the input : {this.state.term} 
      </div> 
     ); 
    }; 

    onInputChange(event) { 
     this.setState({term: event.target.value}) 
    }; } 

export default SearchBar; 

請您幫忙解釋錯誤嗎?

+3

此問題已被詢問並多次回答。綁定'這個',使用箭頭功能。等 – Li357

+0

https://stackoverflow.com/questions/32317154/uncaught-typeerror-cannot-read-property-setstate-of-undefined – HelenA

回答

0

添加到您的構造

this.onInputChange = this.onInputChange.bind(this);

或在你的HTML

<input onChange={e => this.onInputChange(e)}></input>

使用箭頭功能,或在你的課堂上使用箭頭功能

onInputChange = (event) => { ... }

相關問題