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

时间:2019-02-22 02:32:55

标签: javascript reactjs react-props

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

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

我知道在类组件之外没有定义'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;

2 个答案:

答案 0 :(得分:2)

您无需在组件外部创建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;

答案 1 :(得分:1)

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

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

并在您的班级组件上调用此功能:createCheckboxes(this.props.checkboxArray)

顺便说一句,这不是最佳实践。您的复选框应使用Selector

在其父组件上进行编辑