我想要一个文本输入框,它应该在键入时显示建议,如果没有建议,它应该采用键入的输入,否则它应该从建议数组中获取输入。我怎样才能实现这个目标? 我浏览了一些文档和模块react-native-autocomplete-input,但无法理解代码。谁能帮帮我吗?
您也可以像下面这样构建自己的。这样您将可以更好地控制组件并修改行为。
在此示例中,我使用https://callstack.github.io/react-native-paper/text-input.html
import { View } from "react-native";
import { Menu, TextInput } from "react-native-paper";
import { bs } from "../../styles";
import React, { useState } from "react";
const Autocomplete = ({
value: origValue,
label,
data,
containerStyle,
onChange: origOnChange,
icon = 'bike',
style = {},
menuStyle = {},
right = () => {},
left = () => {},
}) => {
const [value, setValue] = useState(origValue);
const [menuVisible, setMenuVisible] = useState(false);
const [filteredData, setFilteredData] = useState([]);
const filterData = (text) => {
return data.filter(
(val) => val?.toLowerCase()?.indexOf(text?.toLowerCase()) > -1
);
};
return (
<View style={[containerStyle]}>
<TextInput
onFocus={() => {
if (value.length === 0) {
setMenuVisible(true);
}
}}
// onBlur={() => setMenuVisible(false)}
label={label}
right={right}
left={left}
style={style}
onChangeText={(text) => {
origOnChange(text);
if (text && text.length > 0) {
setFilteredData(filterData(text));
} else if (text && text.length === 0) {
setFilteredData(data);
}
setMenuVisible(true);
setValue(text);
}}
value={value}
/>
{menuVisible && filteredData && (
<View
style={{
flex: 1,
backgroundColor: 'white',
borderWidth: 2,
flexDirection: 'column',
borderColor: 'grey',
}}
>
{filteredData.map((datum, i) => (
<Menu.Item
key={i}
style={[{ width: '100%' }, bs.borderBottom, menuStyle]}
icon={icon}
onPress={() => {
setValue(datum);
setMenuVisible(false);
}}
title={datum}
/>
))}
</View>
)}
</View>
);
};
export default Autocomplete;
<Autocomplete
value={'Honda'}
style={[style.input]}
containerStyle={[bs.my2]}
label="Model"
data={['Honda', 'Yamaha', 'Suzuki', 'TVS']}
menuStyle={{backgroundColor: 'white'}}
onChange={() => {}}
/>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
containerStyle={styles.autocompleteContainer}
//data to show in suggestion
data={films.length === 1 && comp(query, films[0].title) ? [] : films}
//default value if you want to set something in input
defaultValue={query}
/*onchange of the text changing the state of the query which will trigger
the findFilm method to show the suggestions*/
onChangeText={text => this.setState({ query: text })}
placeholder="Enter the film title"
renderItem={({ item }) => (
//you can change the view you want to show in suggestion from here
<TouchableOpacity onPress={() => this.setState({ query: item.title })}>
<Text style={styles.itemText}>
{item.title} ({item.release_date})
</Text>
</TouchableOpacity>
)}
/>
从 aboutreact.com 得到这个,这里的评论解释了你想要传递到特定区域的内容。我建议尝试为 data 属性传递一个数组。