反应过滤列表

时间:2018-08-08 12:41:03

标签: reactjs filter callback react-dom

我无法在下面的代码笔中弄清楚回调函数的逻辑。

按原样,当用户在输入字段中输入值时,列表将被过滤。如果过滤器被删除,我不知道如何重新显示列表。

https://codepen.io/benszucs/pen/BPqMwL?editors=0010

  class Application extends React.Component {
  state = {
    options: ['Apple', 'Banana', 'Pear', 'Mango', 'Melon', 'Kiwi']
  }
  handleFilter = (newFilter) => {
    if (newFilter !== "") {
      this.setState(() => ({
        options: this.state.options.filter(option => option.toLowerCase().includes(newFilter.toLowerCase()))
      }));
    }
  };
  render() {
    return (
      <div>
        <Filter handleFilter={this.handleFilter} />
        {this.state.options.map((option) => <p>{option}</p>)}
      </div>
    );
  };
}

const Filter = (props) => (
  <div>
    <input name="filter" onChange={(e) => {
        props.handleFilter(e.target.value);
      }}/>
  </div>
);

ReactDOM.render(<Application />, document.getElementById('app'));

2 个答案:

答案 0 :(得分:4)

由于您要覆盖状态的原始值,因此无法将其取反。我建议创建一个名为filter的新状态,并在onChangeHandler()中更新其值。并且在render()方法中,应在显示结果之前过滤结果。

示例:

// the state
this.state = {
    users: ['abc','pdsa', 'eccs', 'koi'],
    filter: '',
}

// the change handler
onChangeHandler(e) {
    this.setState({
        filter: e.target.value,
    });
}

// displaying the results
const list = this.state.users.filter(u => u.includes(this.state.filter)).map(u => (
    <li>{u}</li>
));

答案 1 :(得分:1)

在句柄过滤器中,您可以将状态设置为其默认值

handleFilter = (newFilter) => {
    if (newFilter !== "") {
      this.setState(() => ({
        options: this.state.options.filter(option => option.toLowerCase().includes(newFilter.toLowerCase()))
      }));
    } else {
      this.setState(() => ({
        options: ['Apple', 'Banana', 'Pear', 'Mango', 'Melon', 'Kiwi']
      }));
    }

https://codepen.io/RACCH/pen/pZxMRJ