所以我想做一个搜索过滤器。当前问题是我只能在数据中搜索title
,但我想搜索data
。
基本上,我只能搜索Cluster1
和Cluster2
,但实际上我想搜索fun
和cheerful
部分。
这是我的整个组成部分
const ClusterData = [
{title: 'Cluster1', data: [{name: 'passionate'},{name: 'rousing'},{name: 'confident'},{name: 'boisterous'},{name: 'rowdy'}]},
{title: 'Cluster2', data: [{name: 'rollicking'},{name: 'cheerful'},{name: 'fun'},{name: 'sweet'},{name: 'amiable'},{name: 'natured'}]}
]
let userInput = ''
export default class TempScreen extends React.Component {
constructor(props){
super(props)
this.state = {
search: false,
dataToShow: []
}
}
componentWillMount(){
this.setState({dataToShow: ClusterData})
}
searchUpdated = (term) => {
let matchedItemsArray = []
if(term === ''){
this.setState({search: false, dataToShow: ClusterData})
}else{
this.setState({search:true, dataToShow: ClusterData}, function(){
this.state.dataToShow.map((item) => {
if(item.title.includes(term)){
matchedItemsArray.push(item)
}
})
this.setState({dataToShow:matchedItemsArray})
})
}
}
render () {
return (
<View>
<TextInput
onChangeText={(term) => {this.searchUpdated(term)}}
style={styles.searchInput}
placeholder="Type a mood to search"/>
<SectionList
renderItem={({item}) => <SectionListItem itemName = {item.name}/>}
renderSectionHeader={({section}) => <SectionHeader sectionTitle = {section.title}/>}
sections={this.state.dataToShow}
/>
</View>
)
}
}
class SectionHeader extends React.Component{
render(){
return(
<View>
<Text>{this.props.sectionTitle}</Text>
<TouchableOpacity>
<Text>Play</Text>
</TouchableOpacity>
</View>
)
}
}
class SectionListItem extends React.Component{
render(){
return(
<View>
<Text>{this.props.itemName}</Text>
</View>
)
}
}
答案 0 :(得分:0)
您可以尝试嵌套第二个.map:
searchUpdated = (term) => {
let matchedItemsArray = []
if(term === ''){
this.setState({search: false, dataToShow: ClusterData})
}else{
this.setState({search:true, dataToShow: ClusterData}, function(){
this.state.dataToShow.map((item) => {
item.map((data) => {
if(data.name.includes(term)){
matchedItemsArray.push(data)
}
})
})
this.setState({dataToShow:matchedItemsArray})
})
}
}
答案 1 :(得分:0)
请对您的代码进行大量更新,然后尝试
searchUpdated = (term) => {
let matchedItemsArray = []
if(term === ''){
this.setState({search: false, dataToShow: ClusterData})
}else{
this.setState({search:true, dataToShow: ClusterData}, function(){
ClusterData.map((item) => {
item.data.map(item1=>{
if(item1.name == term){
matchedItemsArray.push(item)
}
})
})
this.setState({dataToShow:matchedItemsArray})
})
}
}