javascript - React - 调用父组件中的函数来访问状态

标签 javascript reactjs jsx

我试图构建一个简单的计算器应用程序来开始使用 React。我试图从子组件中调用根组件中的函数来访问当前状态。我能够调用该函数,但无法访问状态,因为我想更新状态。下面是我的代码:

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
            numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            actions: ['=','+','-','*','/','.','C']
        }
    }


    appendThisNumber(number,oldcount){
        let newCount=parseInt(oldcount.toString()+number.toString()); 
        console.log('New number '+newCount);
        //below code errors out 
        this.setState({
            count:newCount 
        });

    };
    performThisAction(action, oldcount){
        // stuff to do
    };
    render() {

        return (
            <div>
                <CounterDiv countNow={this.state.count} />
                <div>
                    {this.state.numbers.map((n) => <NumButton NumValue={n} countNow={this.state.count} onClickFunction={this.appendThisNumber}/>)}
                </div>
                <div>
                    {this.state.actions.map((a) => <ActionButtons actionItem={a} countNow={this.state.count} onClickFunction={this.performThisAction}/>)}
                </div>

            </div>
        );
    }
}


class CounterDiv extends React.Component {
    render() {
        return (
            <div>
                <input type='text' readOnly value={this.props.countNow} />
            </div>
        );
    }
}

class NumButton extends React.Component {
    handleClick(){
        this.props.onClickFunction(this.props.NumValue,this.props.countNow);
    }

    render() {
        return (
            <button onClick={()=>this.handleClick()} value={this.props.NumValue}>{this.props.NumValue}</button>
        );
    }
}

class ActionButtons extends React.Component{
    handleClick(){
        this.props.onClickFunction(this.props.actionItem,this.props.countNow);
    }
    render() {
        return (
            <button onClick={()=>this.handleClick()} value={this.props.actionItem} label={this.props.actionItem}>{this.props.actionItem}</button>
        );
    }
}
export default App;

我做错了什么或者我需要使用一些数据绑定(bind)框架吗? 提前致谢

最佳答案

您需要将 appendThisNumber() 绑定(bind)到 this

在构造函数中将其绑定(bind)为:

 this.appendThisNumber = this.appendThisNumber.bind(this);

关于javascript - React - 调用父组件中的函数来访问状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51647975/

相关文章:

javascript - ReactJS-目录选择对话框不起作用

javascript - 在匹配(正则表达式)中使用变量 JSON 名称

javascript - 在 protected 路由中进行身份验证登录

javascript - 如何将元素放在垂直对齐的中间?

javascript - Redux 中的 store.dispatch 是同步的还是异步的

javascript - react map 以行渲染

android - React-Native 更改 iOS 和 Android 文件夹的默认位置

javascript - 三元运算符与逻辑运算符

javascript - 如何在单击第 3 方按钮时设置断点?

javascript - 如何在reactjs中获取下拉输入的默认值