如何过滤包含多个字段的列表?我所拥有的程序有一个数据列表,其中有2个过滤器:work
和city
,但是如果我同时选择这两个过滤器,则它不会同时采用这两个字段,只会过滤先前选择的字段。< / p>
如何使用这两个字段过滤此程序?
答案 0 :(得分:1)
您可以在render()
函数和filter
内使用局部变量两次,具体取决于所述过滤器是否打开。
我在下面发布了一个简单的演示。输入全名或城市以过滤列表。
class MyApp extends React.Component {
constructor() {
super();
this.state = {
filterName: "",
filterCity: "",
friends: [
{id: 1, name: "Carl", city: "New York"},
{id: 2, name: "Anna", city: "New York"},
{id: 3, name: "Carl", city: "Sydney"}
]
};
}
changeFilterName = (e) => {
this.setState({filterName: e.target.value});
}
changeFilterCity = (e) => {
this.setState({filterCity: e.target.value});
}
render() {
let friends = this.state.friends.slice();
if(this.state.filterName) {
friends = friends.filter(item => item.name.toLowerCase() == this.state.filterName.toLowerCase());
}
if(this.state.filterCity) {
friends = friends.filter(item => item.city.toLowerCase() == this.state.filterCity.toLowerCase());
}
return(
<div>
<label for="name">Name: </label>
<input id="name" onChange={this.changeFilterName} value={this.state.filterName} />
<label for="city">City: </label>
<input id="city" onChange={this.changeFilterCity} value={this.state.filterCity} />
<ul>
{friends.map(item => <li key={item.id}>{item.name + " - " + item.city}</li>)}
</ul>
</div>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("myApp"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="myApp"></div>
&#13;