为什么我的状态没有更新? [英] Why isn't my state updating?

查看:75
本文介绍了为什么我的状态没有更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究React组件,我不确定为什么我无法将更新功能发送到小部件并使其正确实现.我以为绑定有错误,有人看到过这样的东西吗?

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

推荐答案

您要将方法绑定到父组件.

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

这篇关于为什么我的状态没有更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆