反应 - _this2.SetState不是一个函数

问题描述:

我想创建一个组件,将打印输出文本到屏幕上,这是我正在工作。反应 - _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://*.com/questions/29577977/unable-to-access-react- instance-this-inside-event-handler) – vijayst

试试这个:

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

我认为你需要绑定你的这个,试试这个(没有双关语意)。

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

是的,这也是一个问题,我只是复制并粘贴了他所拥有的。 –

您必须将{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) /> 

我相信你必须指定在该州发生了什么变化:

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

代替

this.SetState(event.target.value)