为什么我的状态没有更新?

Why isn't my state updating?

我正在开发一个 React 组件,我不确定为什么我无法将更新函数发送到小部件并使其正确实现。我想错误出在绑定上,有人见过这样的东西吗?

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component{
    constructor(){
        super();
        this.state = {
            txt: 'this is the state text',
            cat: 0
        }
    }
    update(e){
        this.setState({txt: e.target.value})
    }
    render(){
        let txt = this.props.txt
        return (
            <div>
                <Widget txt={this.state.txt} update={this.update} />
            </div>
        )
    }
}

class Widget extends React.Component{
    render(){
        return (
            <div>
                <input type="text"
                    // this is the error
                    onChange={this.props.update.bind(this) } />
                <h1>{this.props.txt}</h1>
            </div>
        )
    }
}

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

您想将方法绑定到父组件。

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component{
    constructor(){
        super();
        this.state = {
            txt: 'this is the state text',
            cat: 0
        }
    }
    update(e){
        this.setState({txt: e.target.value})
    }
    render(){
        let txt = this.state.txt;
        return (
            <div>
                <Widget txt={this.state.txt} update={this.update.bind(this)} />
            </div>
        )
    }
}

class Widget extends React.Component{
    render(){
        return (
            <div>
                <input type="text"
                    // this is the error
                    onChange={this.props.update} />
                <h1>{this.props.txt}</h1>
            </div>
        )
    }
}

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