Ben*_*ucs 2 callback filter reactjs 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'));
Run Code Online (Sandbox Code Playgroud)
由于您要覆盖状态的原始值,因此您将无法将其取反。我建议创建一个名为的新状态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>
));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1828 次 |
| 最近记录: |