如何在React Hook Form中使用@react-native-community/datetimepicker?

h5qlskok  于 2023-10-22  发布在  React
关注(0)|答案(1)|浏览(160)

我试着做一个日期选择器,当点击一个带有图标和字符串格式的当前日期的字段时,它会出现。
我使用React Native、React Hook Form和@react-native-community/datetimepicker。
偶然间,我在一个无关的问题上找到了一个有趣的答案:https://stackoverflow.com/a/61929764/9927519
我是这样实现的:

const MyComponent = () => {
  const { userData } = useContext(UserDataContext)
  const [isPickerOpen, setIsPickerOpen] = useState(false)
  const parsedBirthday = (userData && userData.birthday && userData.birthday.toDate()) || new Date()
  const [birthday, setBirthday] = useState(parsedBirthday)

  // Validation schema
  const schema = yup.object({
    birthday: yup.date(),
  })

  const { control, handleSubmit, errors } = useForm({resolver: yupResolver(schema)})

  const onSubmit = async (data: any) => {
    console.log(data)
  }

  const datePickerHandler = (selectedDate: Date) => {
    const currentDate = selectedDate || birthday
    if (Platform.OS === 'android') setIsPickerOpen(false)
    setBirthday(currentDate)
  }

  const showDatePicker = () => {
    setIsPickerOpen(true)
  }

  return (
    <View style={styles.fieldContainer}>
      <Text style={styles.helper}>Birthday</Text>
      <TouchableHighlight activeOpacity={0.6} underlayColor="#DDDDDD" onPress={showDatePicker} style={styles.birthday}>
        <>
          <Icon name="calendar-edit" size={32} color={colors.black} />
          <Controller
            control={control}
            render={({ onChange, onBlur, value }) => (
              <TextInput
                style={styles.birthdayText}
                value={birthday.toLocaleDateString()}
                editable={false}
                pointerEvents="none"
                onTouchStart={() => showDatePicker()}
              />
            )}
            name="birthdayString"
            defaultValue={birthday.toLocaleDateString() || new Date().toLocaleDateString()}
          />
        </>
      </TouchableHighlight>
      {/* Date picker */}
      {isPickerOpen && (
        <Controller
          control={control}
          render={({ onChange, onBlur, value }) => (
            <>
              <View>
                <DateTimePicker
                  minimumDate={new Date(1901, 0, 1)}
                  maximumDate={new Date()}
                  value={value}
                  mode="date"
                  display="default"
                  onChange={(event, value) => {
                    datePickerHandler(value)
                  }}
                />
               </View>
            </>
          )}
          name="birthday"
          defaultValue={birthday}
        />
      )}
      <Text style={styles.errorText}>{errors?.birthday}</Text>
    </View>
  )

这一个有点难,因为当提交值时,拾取器是卸载的。然后,我们需要一个TextInput组件来保存该值。
我想知道是否有更好的方法。我有些小小的担忧:

  • 我将字符串转换为日期,然后转换为字符串,然后我需要在提交时将其转换回日期。实际上.toLocaleDateString会使提交变得非常复杂。这可能是国际化的一个问题。
  • onTouchStart不能与鼠标配合使用,只能与触摸设备配合使用。这可能是Chromebook的一个问题。
vnzz0bqm

vnzz0bqm1#

要将@react-native-community/datetimepicker与React Hook Form一起使用,您可以这样做:
1.创建一个将日期选择器与窗体集成的自定义组件。

const DatePicker = ({ control, name, value, onChange }) => {
  return (
    <Controller
      control={control}
      name={name}
      defaultValue={value}
      render={({ field: { onChange, value } }) => (
        <DateTimePicker
          value={value || new Date()} // Provide a default value if value is empty
          mode="date" // You can use "time" or "datetime" for different modes
          is24Hour={true}
          display="default"
          onChange={(event, selectedDate) => {
            onChange(selectedDate);
          }}
        />
      )}
    />
  );
};

1.现在,您可以在表单中使用DatePicker组件。确保您已经使用useForm初始化了表单。

const MyForm = () => {
  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const [selectedDate, setSelectedDate] = useState(null);

  const onSubmit = (data) => {
    // Handle form submission with the selectedDate and other form data
    console.log(data);
  };

  return (
    <View>
      <Text>Select a Date:</Text>
      <DatePicker control={control} name="date" value={selectedDate} onChange={setSelectedDate} />
      <Button title="Submit" onPress={handleSubmit(onSubmit)} />
    </View>
  );
};

export default MyForm;

相关问题