如何修复this.setState不是函数Error

时间:2017-05-27 08:25:14

标签: reactjs

我正在学习React.js,我想构建一个非常基本的嵌套组件示例,它获取一个名称并在屏幕上打印它。当我刷新页面时,我可以看到页面的内容,但是当我给页面命名时,我得到this.setState不是函数错误。我怎样才能解决这个问题?

这是我的代码:

    class GreeterMessage extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            name: this.props.name,
            message: this.props.message
        };
    }

    static get defaultProps() {
        return {
            name: 'Milad',
            message: 'Simple React App'
        };
    }

    render() {
        var name = this.state.name;
        var message = this.state.message;
        return (
            <div>
                <h1>Hello {name}!</h1>
                <p>{message}</p>
            </div>
        );
    }
};

class GreeterForm extends React.Component {

    constructor(props) {
        super(props);
        this.onButtonClick = this.onButtonClick.bind(this);
    }

    onButtonClick(event) {
        event.preventDefault();
        var name = this.refs.name.value;
        this.props.onNewName(name);
        this.refs.name.value = '';
    }

    render() {
        return (
            <div>
                <input type="text" ref="name" /> <br/><br/>
                <input type="button" value="Set Name" onClick={this.onButtonClick} />
            </div>
        );
    }

};

class Greeter extends React.Component {

    constructor(props) {
        super(props);
    }

    handleNewName(name) {
        this.setState({
            name: name,
        });
    }

    render() {
        return (
            <div>
                <GreeterMessage />
                <GreeterForm onNewName={this.handleNewName} />
            </div>
        );
    }
};

ReactDOM.render(
    <Greeter />,
    document.getElementById('app')
);

1 个答案:

答案 0 :(得分:0)

您需要将this绑定到您的函数handleNewName

在你的构造函数中执行:

class Greeter extends React.Component {

    constructor(props) {
        super(props);
        this.handleNewName = this.handleNewName.bind(this);
    }