【问题标题】:React Bootstrap Dropdown items does not update on state changeReact Bootstrap Dropdown 项目不会在状态更改时更新
【发布时间】:2020-06-25 17:40:42
【问题描述】:

使用react-bootstrap 制作带有复选框列表的下拉菜单。当我单击复选框时,切换事件有效,但不会重新呈现组件,并且复选框不会更改。

这里是下拉组件:

type Props = {
  checkboxList: Array<string>;
  title: ReactNode;
  activeCheckboxes: Array<string>;
  onToggle: (string) => void;
  textFormatter: (string) => string;
}

type State = {
  open: boolean;
  activeCheckboxes: Array<string>;
}

class CheckboxDropdown extends React.PureComponent<Props, State> {
  static propsType = {
    checkboxList: PropTypes.array,
    title: PropTypes.string,
    activeCheckboxes: PropTypes.array,
    onToggle: PropTypes.func,
  }

  state: State2;

  constructor(props) {
    super(props);
    this.state = {
      open: false,
      activeCheckboxes: this.props.activeCheckboxes
    };
  }

  static getDerivedStateFromProps(props, state): any {
    if (props.activeCheckboxes.length !== state.activeCheckboxes.length) {
      return {
        activeCheckboxes: props.activeCheckboxes
      };
    }
    return null;
  }

  handleToggle(isOpen, event, metadata): void {
    if (isOpen || metadata.source !== 'select') {
      this.setState(() => ({ open: isOpen }));
    }
    if (event) {
      event.persist();
    }
  }

  render(): ReactNode {
    const { open, activeCheckboxes } = this.state;
    const { checkboxList, title, onToggle, textFormatter } = this.props;

    return (
      <Dropdown
        show={open}
        onToggle={this.handleToggle.bind(this)}
      >
        <Dropdown.Toggle id="dropdown-basic">
          {title}
        </Dropdown.Toggle>
        <Dropdown.Menu>
          {checkboxList.map((chkBox) => (
            <Dropdown.Item key={chkBox}>
              <input type="checkbox" onChange={() => onToggle(chkBox)} checked={activeCheckboxes.includes(chkBox)} />{chkBox}
            </Dropdown.Item>
          ))}
        </Dropdown.Menu>
      </Dropdown>
    );
  }
}

用法:

     <CheckboxDropdown 
       checkboxList={FILTER_LIST}
       activeCheckboxes={activeFilter}
       title={"Dropdown"} />}
       onToggle={this.onToggleCheckbox.bind(this)}
     />

切换复选框更新 activeFilters。当 activeFilters 更改复选框更新时,我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs react-bootstrap react-props react-state-management


    【解决方案1】:

    我不确定这个解决方案是如何工作的。我正在观察在输入中将 onChange 更改为 onClick 并且停止事件传播正在更新复选框。 https://codesandbox.io/s/frosty-bhabha-irhxc

    < input
    type = "checkbox"
    onClick = {
      e => {
        onToggle(chkBox);
        e.stopPropagation();
      }
    }
    checked = {
      activeCheckboxes.includes(chkBox)
    }
    />

    【讨论】:

    • 这似乎对我有用,但我觉得这不是一个理想的解决方案,因为它会在不使用 checkedonChange 处理程序的情况下产生警告。建议使用defaultChecked。我不想使用它,因为我仍然希望复选框的值响应状态更改以及单击它。
    猜你喜欢
    • 2021-09-07
    • 1970-01-01
    • 2021-12-25
    • 2020-07-18
    • 2019-04-10
    • 2020-05-08
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多