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

时间:2018-08-02 07:33:17

标签: 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;

我在做错什么,还是需要使用一些数据绑定框架? 预先感谢

2 个答案:

答案 0 :(得分:2)

您需要将appendThisNumber()绑定到this

在您的构造函数中将其绑定为:

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

答案 1 :(得分:1)

您需要在课程中bind进行操作:

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

有关更多信息,请参见the official doc on "Handling events"