应该过滤列表的简单反应组件。不工作,我不明白为什么......
import React from 'react';
class Filter extends React.Component {
state = {
input: '',
items: [{name: 'lol'}]
}
handleChange = (event) => this.setState({ input: event.target.value })
render(){
const { input, items } = this.state;
return(
<div>
<input
placeholder="search for an item"
onChange={this.handleChange}
/>
{items.filter(term => term.includes(input)).map((term) => (
<div>{term.name}</div>
))}
</div>
)
}
}
export default Filter;
逐字过滤数组,然后映射到它......
答案 0 :(得分:0)
import React from 'react';
class Filter extends React.Component {
state = {
input: '',
items: [{name: 'lol'}],
filteredItems: false,
}
filter(e) {
var value = e.target.value;
this.setState({filterval: value})
this.setState({
filteredItems: !value
? false
: this.state.items.filter(function (item) {
return item.name.toLowerCase().indexOf(value.toLowerCase()) !== -1;
})
})
}
render(){
var list = this.state.filteredItems || this.state.items || []
return (
<div>
<input placeholder="search for an item" onChange={this.filter.bind(this)}
/>
<div>
{list.map((item,index) => (
<div>{term.name}</div>
))}
</div>
</div>
)
答案 1 :(得分:0)
items.filter(term => term.includes(input))
这里的情况不正确。变量term
是一个对象{name: 'lol'}
。 includes
不适用于对象。
它应该是term.name.includes(input)
或term.name === input