繁体   English   中英

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

[英]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')
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM