我正在尝试弄清楚如何将参数/ Prop 传递给来自 React Native Paper 的输入,因为 React Native Paper 没有合适的下拉菜单,所以有一个我喜欢的“菜单”在我的项目上实现,但文档太糟糕了,没有关于如何从该项目获取元素的示例,也没有将该参数传递给其他地方。
<TextInput
style={{width: 300, backgroundColor: 'transparent', margin: 0, padding: 0}}
label='Email'
value={Username}
onChangeText={User => setUsername(User)}
/>
如你所见,这是菜单
<Provider>
<Menu
visible={isOpen}
onDismiss={() => setOpen(false)}
anchor={
<Button style={{marginTop: 25}} color="#8DB600" icon="account" dark={true} mode="contained" onPress={() => setOpen(true)}>
Ingresar
</Button>
}>
<Menu.Item onPress={() => {}} title="Item 1" />
<Menu.Item onPress={() => {}} title="Item 2" />
<Menu.Item onPress={() => {}} title="Item 3" />
</Menu>
</Provider>
我的想法是按下 anchor 上的那个按钮,显示菜单并选择一个项目,然后那个项目显示在文本输入上,就像我在这个组件中输入一样
最佳答案
假设文本输入和下拉菜单都是同一个组件的一部分 - 使用 setUsername 更改 Username
的值将更新文本输入
const [Username, setUsername] = useState(''); // both components must have access to Username state
<TextInput
style={{width: 300, backgroundColor: 'transparent', margin: 0, padding: 0}}
label='Email'
value={Username}
onChangeText={User => setUsername(User)}
/>
<Provider>
<Menu
visible={isOpen}
onDismiss={() => setOpen(false)}
anchor={
<Button style={{marginTop: 25}} color="#8DB600" icon="account" dark={true} mode="contained" onPress={() => setOpen(true)}>
Ingresar
</Button>
}>
<Menu.Item onPress={() => setUsername("Item 1")}} title="Item 1" /> // directly set username like this
<Menu.Item onPress={() => setUsername("Item 2")} title="Item 2" />
<Menu.Item onPress={() => setUsername("Item 3")} title="Item 3" />
</Menu>
</Provider>
为什么这有效 - doc
The value to show for the text input. TextInput is a controlled component, which means the native value will be forced to match this value prop if provided.
编辑:完整的工作示例 - https://snack.expo.io/4I0Xr0HBR
关于javascript - 我如何将所选项目从 React Native Paper Menu 传递到 Input/TextInput onChangeText 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61604500/