簡體   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