
[英]onPress on picker.item to close the dropdown- react-native
[英]React-Native: Expo stops when I add Picker item
我是 react-native 的新手,我正在尝试使用 Picker 项目从下拉列表中进行选择,我正在使用反应挂钩将 Picker 项目设置为可选,但是当我添加代码时 Expo 会在没有警告的情况下停止:
const HomeScreen3 = observer(() =>
{
const [ options, setOptions ] = useState([ { id:1, title:'Titulo 1' }, { id:2, title:'Titulo 2' } ]);
const [ selectedOption, setSelectedOption ] = useState({ id:1, title:'Titulo 1' });
useEffect(() => {
console.log('component mounted');
}, []);
return (
<View style={{flex: 1, backgroundColor: '#fff', padding:10, position:'relative' }}>
<ScrollView showsHorizontalScrollIndicator={false}>
<Picker
itemStyle={{ backgroundColor: "white", color: "black", borderColor:'rgba(0,0,0,0.2)', fontSize:16, }}
mode="dropdown"
selectedValue={selectedOption}
onValueChange={(value) => { setSelectedOption( value)}}>
{options.map((item, index) => {
return (<Picker.Item label={item} value={item} key={index}/>)
})}
</Picker>
</ScrollView>
</View>
export default HomeScreen3;
首先,在 Expo SDK 38 中import { Picker } from 'react-native';
不再按预期工作。
确保您使用import { Picker } from '@react-native-community/picker';
这是它的文档: https://github.com/react-native-community/react-native-picker 。
其次,我看到的真正问题是您的代码的问题是Picker.Item
的问题,这里:
{options.map((item, index) => {
return (<Picker.Item label={item} value={item} key={index}/>)
})}
您正在发送label
和item
道具中的完整对象。 但是,查看实际文档, label 接受字符串,值接受字符串或 integer - https://reactnative.dev/docs/picker-item
这意味着您的Picker
代码应如下所示:
<Picker
itemStyle={{backgroundColor: "white", color: "black", borderColor:'rgba(0,0,0,0.2)', fontSize:16}}
mode="dropdown"
selectedValue={selectedOption}
onValueChange={(value) => {setSelectedOption(value)}}>
{options.map((item, index) => {
return (<Picker.Item label={item.id} value={item.title} key={index}/>)
})}
</Picker>
并且selectedOption
应该只存储项目的 id,如下所示:
const [ selectedOption, setSelectedOption ] = useState(1);
对于 expo 使用这对我有用,即使有警告但有效!
import { Picker } from 'react-native'
// state
const [picked, setPicked] = useState(1.15);
<Picker
selectedValue={picked}
style={{ height: 50, width: 100 }}
onValueChange={(itemValue, itemIndex) =>
setPicked(itemValue)
}>
<Picker.Item label="Canda 5%" value={1.05} />
<Picker.Item label="Japan 8%" value={1.08} />
<Picker.Item label="USA 10%" value={1.10} />
<Picker.Item label="Egypt 14%" value={1.14} />
<Picker.Item label="Saudi Arabia 15%" value={1.15} />
<Picker.Item label="China 16%" value={1.16} />
<Picker.Item label="Algeria 17%" value={1.17} />
<Picker.Item label="18%" value={1.18} />
<Picker.Item label="German 19%" value={1.19} />
<Picker.Item label="German 19%" value={1.20} />
</Picker>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.