如何从@react-native-community/datetimepicker 获取日期值并将其存储在对象中以供用户使用

How to get the value of date from @react-native-community/datetimepicker and store it in for a user in an object

我正在为用户构建一个注册页面,他们可以从我从“@react-native-community/datetimepicker”使用的日期选择器中 select 他们的出生日期。一切正常,代码能够在屏幕上显示 selected 日期,而且所有其他字段的数据都存储在 userInfo 对象中,除了 出生日期。 这是我使用日期选择器的代码部分:

(您可以忽略 formatDate 函数,因为它只是将日期格式化为时间戳)

            <Text style={[styles.text_footer,{marginTop:10}]}>Date Of Birth</Text>
            <View style={[styles.action,{paddingTop:5}]}>
                <FontAwesome
                name="calendar"
                color="#05375a"
                size={20}
                onPress={showDatepicker}
                />
                {show && (
                    <DateTimePicker
                    testID='dateTimePicker'
                    value={date}
                    mode={mode}
                    is24Hour={true}
                    display='default'
                    onChange={onChange}
                    //onChange={(val)=>handleOnChangeText(val,'dateOfBirth')}
                    />
                )}
                <Text style={[styles.textInput,{paddingTop:10}]}>{formatDate(date)}</Text>
            </View>

并且用到的函数和状态是:

    const [date, setDate] = useState(new Date());
    const [mode, setMode] = useState('date');
    const [show, setShow] = useState(false);

    const [userInfo, setUserInfo]=React.useState({
        email:'',
        password:'',
        gender:'',
        age:null,
        dateOfBirth:'',
        address:'',
        role:'',
        check_textInputChange:false,
        secureTextEntry:true,
        isValidUser: true,
        isValidPassword: true,
        isValidAge:true,
        isValidAddress:true
    });

    const {email,password,gender,age,dateOfBirth,address,role}=userInfo;


    const onChange = (event, selectedValue) => {
        setShow(Platform.OS === 'ios');
        if (mode == 'date') {
          const currentDate = selectedValue || new Date();
          setDate(currentDate);
        } 
      };
    const showMode = currentMode => {
        setShow(true);
        setMode(currentMode);
      };
    const showDatepicker = () => {
        showMode('date');
      };
    const handleOnChangeText= (val,fieldname)=>{
        setUserInfo({...userInfo,[fieldname]:val})
        //console.log(val,fieldname);
    };
//If I console.log(userInfo) here then the state dateOfBirth is not getting updated 

还有一个电子邮件示例以及我如何使用 handleOnChangeText 函数:

(这是有效的。附加只是为了理解目的,请忽略 textInputChangehandleValidUser 函数)

            <Text style={styles.text_footer}>Email</Text>
            <View style={styles.action}>
                <FontAwesome
                name="user-o"
                color="#05375a"
                size={20}
                />
                <TextInput
                value={email}
                placeholder="Your Email" 
                style={styles.textInput}
                autoCapitalize="none"
                onChangeText={(val)=>{textInputChange(val);handleOnChangeText(val,'email');}}
                onEndEditing={(e)=>handleValidUser(e.nativeEvent.text)}
                />
                {userInfo.check_textInputChange?
                <Animatable.View
                    animation="bounceIn"
                >
                <Feather
                name="check-circle"
                color="green"
                size={20}
                />
                </Animatable.View>
                :null}
            </View>
            {
                userInfo.isValidUser?null:
            <Animatable.View animation="fadeInLeft" duartion={500}>
             <Text style={styles.errorMsg}>Username must be 4 characters long.</Text>       
             </Animatable.View>
            } 

记录userInfo后的对象输出

如何获取 userInfo 中 dateOfBirth 的值?

这可能是由于您的代码中存在一个小错误。您传递给 DateTimePickerDate change handler 永远不会调用 handleOnChangeText:

<DateTimePicker
    testID='dateTimePicker'
    value={date}
    mode={mode}
    is24Hour={true}
    display='default'
    onChange={onChange} // <--- this one
    //onChange={(val)=>handleOnChangeText(val,'dateOfBirth')}
/>

更新处理程序应该可以解决您的问题:

const onChange = (event, selectedValue) => {
    setShow(Platform.OS === 'ios');
    if (mode == 'date') {
        const currentDate = selectedValue || new Date();
        setDate(currentDate);
        handleOnChangeText(currentData, 'dateOfBirth') // <--- add this line
    } 
};