【问题标题】:ReactJS Using child props in parent classReactJS 在父类中使用子道具
【发布时间】:2019-07-27 20:39:47
【问题描述】:

我有一个父类,它使用它的子类从数组“days”中呈现一些按钮。到目前为止,这工作正常。我使用处理程序将 handleClick() 传递给孩子。这也有效,如果没有 if 语句,我会在控制台中获得返回。我的代码有什么问题或考虑 if 语句有什么问题。 如果我单击值为 days[0] = 1 的按钮,它应该回复“Hi 1”。

家长:

export default class Parent extends React.Component {

  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.state = {
      days: [1,2,3]
    }

  }

  handleClick() {
      if(this.props.value === 1) {
      return console.log('Hi 1')
    }
  }

  render() {
    return (
      <div>
          <div>
            {this.state.days.map(item => <ButtonDays handler={ () => this.handleClick()} key={item} value={item} />)}
          </div>
      </div>
    );
  }
}

孩子:

export default class ButtonDays extends React.Component { 
  render() {
    return (
      <Button onClick={this.props.handler}>{this.props.value}</Button>
    );
  }
}

【问题讨论】:

  • 我不明白什么...你希望当子按钮被点击时,它基本上是 console.log Hi 及其来自父级的值?
  • this.props.valueParent 类中是undefined

标签: reactjs onclick state react-props


【解决方案1】:

在你父组件的下面部分

handleClick() {
  if(this.props.value === 1) {
    return console.log('Hi 1')
  }
}

您正在检查名为 value 的道具,但此道具仅在您的子组件中定义。

您应该做的是将点击的值作为handler 函数的参数传递。

<Button onClick={() => this.props.handler(this.props.value)}>{this.props.value}</Button>

然后在你的父组件中:

handleClick(value) {
  if(value === 1) {
    return console.log('Hi 1')
  }
}

【讨论】:

  • 您好 Arnaud,非常感谢您的回答,看来我们是 / 我绝对是正确的方式!如果我像你那样做,建议'Hi 1'仍未打印。但如果我将 handleClick() 设置为 `handleClick(value) { return console.log({value}) }',我会返回:Object { value: undefined }
  • 实际上我没有注意到您正在返回console.log 的结果。您可以删除退货并保留console.log("Hi 1")
猜你喜欢
  • 1970-01-01
  • 2021-03-12
  • 2021-01-26
  • 1970-01-01
  • 2016-11-03
  • 2017-03-18
  • 1970-01-01
  • 2015-12-02
  • 2016-09-18
相关资源
最近更新 更多