反应本机 DateTimePicker 将初始状态设置为字符串

react native DateTimePicker set initial state to String

我正在尝试实现 react-native-datetimepicker,我想设置一个初始状态文本“编辑出生日期”而不是当前的今天日​​期,有人可以指导我如何实现吗?看来我不能在日期挂钩中使用字符串作为值。

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

  const onChange = (event, selectedDate) => {
    const currentDate = selectedDate || date;
    setShow(Platform.OS === 'ios');
    setDate(currentDate);
  };

return (
<Text>{date.toDateString()}</Text>
<DateTimePicker
              testID="dateTimePicker"
              value={date}
              mode={mode}
              is24Hour={true}
              display="default"
              onChange={onChange}/>

如果您还没有选定的日期(初始化为空),则需要一个 Text/Button 组件来显示消息。

const [date, setDate] = useState(null);
const [show, setShow] = useState(false);

const showDate = () => {
   setShow(true)
}

const onChange = (event, selectedDate) => {
   const currentDate = selectedDate || date;
   setShow(Platform.OS === 'ios');
   setDate(currentDate);
};

return (

<View>
<Button onPress={showDate} title={ date ? date.toDateString() : 'Edit Date of Birth'} />

{show && ( 
   <DateTimePicker 
       testID="dateTimePicker" 
       value={date} 
       is24Hour={true} 
       display="default" 
       onChange={onChange}/> 
}
</View>

)