reactjs - React - _this2.SetState 不是一个函数

标签 reactjs

我正在尝试创建一个将输入文本打印到屏幕上的组件,这就是我正在做的事情。

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

有什么想法吗?

谢谢

最佳答案

试试这个:

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

关于reactjs - React - _this2.SetState 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39705002/

相关文章:

javascript - 如何制作包含空格的关联图

javascript - 循环内的逻辑在 ReactJs 上不起作用

reactjs - 如何使用reactjs在渲染中设置变量?

reactjs - 组件选择器只能和 babel-plugin-emotion 一起使用 使用emotion时报错

javascript - 无法在 react 组件中设置状态

reactjs - 带有React和Firebase登录的Electron弹出问题

javascript - react : Highlight text between two indexes

javascript - 如何在 ReactJS 中正确使用 USParser() 来获取我的计算机 CPU?

react-router - 在redux中间件中使用react-router进行重定向

javascript - WebStorm实时模板: how to create an 'export default from' live template/How to get current folder name?