无法通过父组件方法访问状态

时间:2019-06-06 19:10:34

标签: javascript reactjs

我正在使用道具将方法调用传递给其子组件(键盘和键),但是当我尝试在子组件(键)中执行该方法时,该方法无法访问原始组件(计算器)状态,返回未定义


class Calculator extends React.Component{
  constructor(){
    super()
    this.state = {
      display : "nothing now"
      keys : [
        {
          class: "digit",
          label : "0", 
          id : "zero",
          fn : this.setCalculation  
        }
      ]
    }

    this.setCalculation = this.setCalculation.bind(this)
  }


  setCalculation(){
    console.log(this.state.display) // return undefined when I click a Key Component

  }

  render(){

    return(
      <div id="calculator">
          <Display content={this.state.display}/>
          <Keyboard keys={this.state.keys}/>
      </div>
    )
  }
}

class Keyboard extends React.Component{
  constructor(props){
    super(props)
  }

  render(){
    let keys = this.props.keys.map((v) => {
      return <Key data={v}/>
    })

    return(
      <div id="keyboard">{keys}</div>
    )
  }
}

class Key extends React.Component{
  constructor(props){
    super(props)    
    this.execute = this.execute.bind(this)
  }  

  execute(e){
    this.props.data.fn(this.props.data.label)
  }

  render(){
    return (
      <div className={"key " + this.props.data.class} style={{gridArea : this.props.data.id}} onClick={this.execute}><span>{this.props.data.label}</span></div>
      )
  }
}


ReactDOM.render(<Calculator />,document.getElementById("app"))

需要返回计算器组件状态值的方法

1 个答案:

答案 0 :(得分:1)

除了“现在什么都没有”之后您忘记的逗号之外,您还需要在定义组件状态之前绑定setCalculation方法。

constructor(props) {
  super(props);
  this.setCalculation = this.setCalculation.bind(this);
  this.state = {
    display : "nothing now",
    keys : [
      {
        class: "digit",
        label : "0", 
        id : "zero",
        fn : this.setCalculation  
      },
    ],
  };
}