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

问题描述

我正在为用户构建一个注册页面,他们可以从我从“@react-native-community/datetimepicker”中使用的日期选择器中选择他们的出生日期。一切正常,代码能够在屏幕上显示选定的日期,除dateOfBirth外,所有其他字段的数据都存储在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 的值?

标签: react-nativereact-native-datetimepicker

解决方案


这可能是由于您的代码中的一个小错误。您传递给的日期更改处理程序DateTimePicker永远不会调用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
    } 
};

推荐阅读