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

标签 javascript reactjs bind

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

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

最佳答案

您想要将该方法绑定(bind)到父组件。

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

关于javascript - 为什么我的状态没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34716581/

相关文章:

javascript - Gulp:如何将 gulp 结果作为变量获取

javascript - 显示选定的复选框在 javascript 中不起作用

javascript - Rails 操作仅调用一次,但我在 ajax 中每秒调用一次

javascript - 如果jquery live event代码已被删除,我还需要解绑它吗?

javascript - Google Closure 绑定(bind)/解决 this 关键字的问题

javascript - 由于没有从 express-serve-static-core 导出 ParsedQs,构建失败

reactjs - react 警告 : Function components cannot be given refs

javascript - 无法使用 React hooks 读取未定义的属性 'map'

reactjs - React Native TouchableOpacity OnPress 不使用循环

javascript - jQuery 事件处理逻辑