如何在 class 组件 React 之外访问道具

How to access props outside of a class component React

我无法理解如何访问 React 中 class 组件之外定义的道具。

在下面的代码中定义了除 this.props.checkboxArray 之外的所有道具,目前 returns "cannot read property 'props' of undefined."

我知道 'this' 没有在 class 组件之外定义,所以我尝试将 '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 prop

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

    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
      }),
      {}
    );

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

顺便说一句,这不是最佳做法。应使用 Selector

在其父组件上编辑您的复选框