首页 > 解决方案 > ReactJS 在父类中使用子道具

问题描述

我有一个父类,它使用它的子类从数组“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>
    );
  }
}

标签: reactjsonclickstatereact-props

解决方案


在您的父组件的以下部分

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')
  }
}

推荐阅读