【发布时间】:2019-05-14 16:30:22
【问题描述】:
我正在尝试仅使用一个文本输入为 reactjs 中的对象构建通用/全局搜索。
我尝试了不同的方法,包括将字符串转换为数组,然后使用它来过滤我的对象。我设法通过所有属性进行输入搜索,但当时只有一个。
const data = [
{
name:"Italy",
title:"Best place for Pizza"
},
{
name:"USA",
title:"It is a federal state"
}
]
export class MyApp extends React.Component{
constructor(props){
super(props);
this.state = {
filteredData:[],
filter:''
}
this.handleSearch.bind(this);
}
componentDidMount(){
this.setState({
filteredData:data
})
}
handleSearch = (e) =>{
const filter = e.target.value;
this.setState({
filter
})
}
render(){
var filteredData = data;
var searchValue = this.state.filter;
filteredData = filteredData.filter(country => {
return['name', 'title'].some(key =>{
return country[key].toString().toLowerCase().includes(searchValue)
})
})
return (
<div>
<input type="search" onChange={(e) => this.handleSearch(e)}/>
{
filteredData.map(result =>{
return <p>{result.name} | {result.title}</p>
})
}
</div>
);
}
我想要的是能够组合属性。例如:我希望能够输入“Italy best place for...”并仍然得到结果。我不想仅限于输入“披萨的最佳地点”或“意大利”来获得条目。
【问题讨论】:
-
这是您正在寻找的模糊搜索类型吗?
标签: javascript arrays reactjs object