Why isn't my state updating?

2019-09-04 10:01发布

问题:

I am working on a React component, and i'm not sure why I'm unable to send the update function to the widget and have it implement properly. I imagine the error is with the binding, has anyone seen something like this?

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

回答1:

You want to bind the method to the parent component.

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