【问题标题】:Can't access state from parent component method无法从父组件方法访问状态
【发布时间】:2019-06-06 19:10:34
【问题描述】:

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


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"))

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

【问题讨论】:

  • 在示例中我想打印状态值,而不是返回任何内容。所以不允许我编辑帖子。

标签: javascript reactjs


【解决方案1】:

除了“nothing now”后面的逗号之外,还需要在定义组件状态之前绑定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  
      },
    ],
  };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    相关资源
    最近更新 更多