未捕获的TypeError:无法读取未定义的属性'setState' - 尚未使用ES6

时间:2017-10-04 12:16:56

标签: javascript reactjs

使用Udemy课程学习React。在尝试输出状态值时进入错误:

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;

你能帮忙解释一下这个错误吗?

1 个答案:

答案 0 :(得分:0)

添加到您的构造函数

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

或在HTML中使用箭头功能

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

或在班级中使用箭头功能

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