【问题标题】:Filter button should deselect when another filter is clicked单击另一个过滤器时,过滤器按钮应取消选择
【发布时间】:2018-08-01 23:52:40
【问题描述】:

我有几个按钮来过滤表格中的项目选择。

当用户选择一个按钮时,相应的项目会突出显示。

我需要进行设置,以便在选择另一个过滤器按钮时,清除之前的过滤器选择。

我想要它,因此一次只能进行一个过滤选择。我打算添加一个重置按钮,但我认为用户希望能够在不同的过滤器之间切换,而不必每次都单击重置按钮。

这是我目前拥有的:

export default class FilterIcon extends Component {
  constructor(props) {
    super(props);
    this.state = {
      active: false
    };
    this.filterItem = this.filterItem.bind(this);
  }

  filterItem(id) {
    this.state.active === true
      ? this.props.applyFilter(null)
      : this.props.applyFilter(id);
    this.setState({
      active: !this.state.active
    });
  }

  render() {
    const { id, label } = this.props;
    let boundfilterItem = this.filterItem.bind(this, id);

    return (
      <FilterLink href="#" className={id} onClick={boundfilterItem}>
        {this.state.active === true ? (
          <FilterImage src={Icons[id + "Active"]} id={id} />
        ) : (
          <FilterImage src={Icons[id]} id={id} />
        )}
      </FilterLink>
    );
  }
}

父组件是这样设置的:

export default class Header extends React.Component {
 constructor(props) {
 super(props)
 this.state = {
  isActive: false,
 }
 this.iconToggle = this.iconToggle.bind(this)
}

iconToggle() {
 this.setState({
  isActive: !this.state.isActive,
 })
}

render() {
 return (
   <FilterIcon
      id="1"
       applyFilter={this.props.applyFilter}
    />
    <FilterIcon
       id="2"
       applyFilter={this.props.applyFilter}
     />
     <FilterIcon
       id="3"
       applyFilter={this.props.applyFilter}
     />
   )
 }

}

【问题讨论】:

    标签: javascript reactjs filtering ternary-operator


    【解决方案1】:

    在父组件中,您正在渲染这些FilterIcons 并传递一个label 和一个id 和一个方法applyFilter,你为什么不也传递一个额外的prop active?兄弟组件不直接相互通信,因此它的设计方式是,虽然FilterIcons 在父组件中调用applyFilter,但其兄弟组件FilterIcons 对此调用一无所知。但是,如果在父级的applyFilter 方法中更新包含FilterIconsactive 的数据的数组或对象(可能与labelid 数据并排),您应该很好去。显然,applyFilter 需要比您目前拥有的 filterItem 方法做更多的事情。它需要找到以前的activeFilterIcons去激活它并激活新的。

    【讨论】:

    • 好点。我将用父组件在做什么来更新我的问题。
    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 2016-08-26
    • 1970-01-01
    • 2020-08-30
    相关资源
    最近更新 更多