我尝试创建一个自动完成下拉搜索栏,我找到了Here,并尝试将其与填充数据dataSource
一起使用,效果很好,但当我将其与从API获取的数据一起使用时,它不起作用,请参见下面的代码
- 应用程序js**
const App = () => {
const [dataSource] = useState(['apple', 'banana', 'cow', 'dex', 'zee', 'orange', 'air', 'bottle'])
const [filtered, setFiltered] = useState(dataSource);
const [searching, setSearching] = useState(false);
const onSearch = (text) => {
if (text) {
setSearching(true)
const temp = text.toLowerCase()
const tempList = dataSource.filter(item => {if (item.match(temp))return item})
setFiltered(tempList)
} else {
setSearching(false)
}
}
return (
<SafeAreaView style={styles.container}>
<TextInput
style={styles.textInput}
placeholder="Search"
placeholderTextColor='white'
onChangeText={onSearch}
/>
{ searching &&
<SearchDropDown
dataSource={filtered}
/>
}
</SafeAreaView>
)
}
- 搜索下拉列表. js**
const SearchDropDown = (props) => {
const {dataSource} = props;
return (
<View>
{
dataSource.map((item,index) => {
return (
<View>
<View key={index}>
<Text style={{color: 'black'}}>{item}</Text>
</View>
</View>
)
})
}
</View>
)
}
这是我的代码,我用artistData
替换了dataSource
,它从我的API中获取数据
const [artistData, setArtist] = useState([]);
const [filtered, setFiltered] = useState(artistData);
const [searching, setSearching] = useState(false);
useEffect(() => {
axios.get(serveURL)
.then((response) => setArtist(response.data))
.catch(error => { console.log(error) });
}, []);
const onSearch = (text) => {
if (text) {
setSearching(true)
const temp = text.toLowerCase()
const tempList = artistData.filter(item => {if (item.match(temp))return item})
setFiltered(tempList)
} else {
setSearching(false)
}
}
return (
<SafeAreaView style={styles.container}>
<TextInput
style={styles.textInput}
placeholder="Search"
placeholderTextColor='white'
onChangeText={onSearch}
/>
{ searching &&
<SearchDropDown
artistData={filtered}
/>
}
</SafeAreaView>
)
另外,在SearchDropDown.js
中将const {dataSource} = props;
和dataSource.map
更改为const {artistData} = props;
和artistData.map
,但仍然不起作用,我检查了artistData
中是否有数据与flatlist
,请参见下面
<FlatList
data = {serveURL}
listKey="artist-data"
keyExtractor={item => item.id}
renderItem={({item}) => {
return (
<Text>{item.artist_name}</Text>
)
}}
/>
它显示有数据在那里,请我将需要你的帮助与此,谢谢。
1条答案
按热度按时间rxztt3cl1#
我正在使用
yarn add react-native-autocomplete-dropdown
查看https://www.npmjs.com/package/react-native-autocomplete-dropdown上的完整文档范例
https://snack.expo.dev/@onmotion/react-native-autocomplete-dropdown