反应过滤列表
React filtering a list
我无法理解下面代码笔中回调函数的逻辑。
就目前而言,当用户在输入字段中键入值时,列表会被过滤。如果过滤器被删除,我不知道如何恢复列表。
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'));
由于您正在覆盖状态的原始值,因此您将无法撤消它。我建议创建一个名为 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>
));
在您的句柄过滤器中,您可以将状态设置为其默认值
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/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'));
由于您正在覆盖状态的原始值,因此您将无法撤消它。我建议创建一个名为 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>
));
在您的句柄过滤器中,您可以将状态设置为其默认值
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']
}));
}