繁体   English   中英

如何在类组件React之外访问props

[英]How to access props outside of a class component React

我在理解如何访问React的类组件外部定义的prop时遇到了麻烦。

在下面的代码中,定义了所有道具,但this.props.checkboxArray当前返回“无法读取未定义的属性'道具”。

我知道'this'并未在类组件之外定义,因此我尝试将'this'绑定到checkboxArray,但仍存在未定义'props'的相同错误。

    let checkboxObject = this.props.checkboxArray.reduce(
      (name, boolean) => ({
        ...name,
        [boolean]: false
      }),
      {}
    );

    class CheckboxList extends Component {
      constructor(props) {
        super(props);
        this.state = { checkbox: checkboxObject };

        this.checkboxArray = this.checkboxArray.bind(this);
      }

      handleCheckboxChange = name => {
        let checkbox = this.state.checkbox;
        for (var key in checkbox) {
          if (key === name) {
            checkbox[key] = !checkbox[key];
          }
        }
        this.setState({ checkbox });
      };

      render() {
        return (
          <div className="row" id="CheckboxList">
            {this.props.checkBoxArray.map(checkbox => (
              <Checkbox
                label={checkbox}
                isSelected={checkboxObject[checkbox]}
                onCheckboxChange={this.props.onCheckboxTick}
                key={checkbox}
              />
            ))}
          </div>
    );
  }
}

export default CheckboxList;

您无需在组件外部创建checkboxObject,而是可以像在下面的更新代码中那样在初始化复选框状态时直接在构造函数中进行checkboxArray的减少。 然后使用this.state.checkbox [checkbox]访问isSelected属性

这样您只初始化一次复选框状态这是更新的代码

    class CheckboxList extends Component {
  constructor(props) {
    super(props);
    this.state = { 
        checkbox: this.props.checkboxArray.reduce(
  (name, boolean) => ({
    ...name,
    [boolean]: false
  }),
  {}
); //here you can directly initialize the state
    };

    this.checkboxArray = this.checkboxArray.bind(this);
  }

  handleCheckboxChange = name => {
    let checkbox = this.state.checkbox;
    for (var key in checkbox) {
      if (key === name) {
        checkbox[key] = !checkbox[key];
      }
    }
    this.setState({ checkbox });
  };

  render() {
    return (
      <div className="row" id="CheckboxList">
        {this.props.checkBoxArray.map(checkbox => (
          <Checkbox
            label={checkbox}
            isSelected={this.state.checkbox[checkbox]}
            onCheckboxChange={this.props.onCheckboxTick}
            key={checkbox}
          />
        ))}
      </div>
);
  }
 }

  export default CheckboxList;

您应该创建一个函数来调用checkboxObject,例如:

const createCheckboxes =  checkboxArray => checkboxArray.reduce(
      (name, boolean) => ({
        ...name,
        [boolean]: false
      }),
      {}
    );

并在您的类组件上调用此函数: createCheckboxes(this.props.checkboxArray)

顺便说一句,这不是最佳实践。 您的复选框应使用选择器在其父组件上进行编辑

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM