我是新的反应原生,我想创建一个表单。我使用formik来实现这一点。我还添加了react-native-dropdown-picker,因为react-native的选择器在android上的占位符有问题。我想将我在下拉列表中使用的性别属性传递给state。我有没有办法做到这一点?
import React, {Component} from 'react'
import { StyleSheet, Button, TextInput, View, } from 'react-native'
import { Formik } from 'formik';
import DropDownPicker from 'react-native-dropdown-picker';
export default class Registration extends Component{
render() {
return (
<View>
<Formik
initialValues={{ fullName: '', mobileNumber: '', country: '', gender: '', password: '', email: '' }}
onSubmit={(values) => {
console.log(values)
}}
>
{(props) => (
<View>
<TextInput style={styles.input}
placeholder="Full Name"
onChangeText={props.handleChange('fullName')}
value={props.values.fullName}
>
</TextInput>
<TextInput style={styles.input}
placeholder="Mobile Number"
keyboardType="numeric"
onChangeText={props.handleChange('mobileNumber')}
value={props.values.mobileNumber}
>
</TextInput>
<TextInput style={styles.input}
placeholder="Country"
onChangeText={props.handleChange('country')}
value={props.values.country}
>
</TextInput>
<DropDownPicker
items={[
{label: 'Male', value: 'male'},
{label: 'Female', value: 'female'},
]}
defaultValue={props.values.gender}
placeholder="Select your gender"
containerStyle={{height: 40}}
style={{backgroundColor: '#fafafa'}}
itemStyle={{
justifyContent: 'flex-start'
}}
dropDownStyle={{backgroundColor: '#fafafa'}}
onChangeItem={item => props.setState({
gender: item.value
})}
/>
<TextInput style={styles.input}
placeholder="Email"
onChangeText={props.handleChange('email')}
value={props.values.email}
>
</TextInput>
<TextInput style={styles.input}
placeholder="Password"
secureTextEntry={true}
onChangeText={props.handleChange('password')}
value={props.values.password}
>
</TextInput>
<Button title="Submit" color="blue" onPress={props.handleSubmit}></Button>
</View>
)}
</Formik>
</View>
)
}
}
const styles = StyleSheet.create({
input: {
borderWidth: 1,
borderColor: "#ddd",
padding: 10,
fontSize: 18,
borderRadius: 6
}
})发布于 2020-09-03 01:02:33
我找到了答案。formik有一个名为set field value的方法,可以更新dropdown的状态
<DropDownPicker
items={[
{ label: 'Male', value: 'male' },
{ label: 'Female', value: 'female' },
]}
value={props.values.gender}
placeholder="Select your gender"
containerStyle={{ height: 40 }}
onBlur={props.handleBlur('gender')}
style={{ backgroundColor: '#fafafa' }}
itemStyle={{
justifyContent: 'flex-start'
}}
dropDownStyle={{ backgroundColor: '#fafafa' }}
onChangeItem={item => props.setFieldValue(
'gender', item.value
)}
/>发布于 2021-11-30 18:14:52
在DropDownPicker 5.2版本中,item是一个函数。不得不做的事情:
<DropDownPicker
...
onChangeItem={item => props.setFieldValue(
'gender', item()
)}
/>https://stackoverflow.com/questions/63691298
复制相似问题