1

有没有办法以编程方式打开/关闭日期选择器react-native-datetimepicker

我的用例是创建一个组件,该组件TouchableOpacity在按下时会打开 DatePicker(表面积比微小的日期选择器大得多)。

RNDateTimePicker似乎不接受 a ref,也没有隐藏/显示的 API。

非常感谢。

4

1 回答 1

1

文档页面有演示。控制显示状态隐藏或显示日期选择器。

import React, {useState} from 'react';
import {View, Button, Platform} from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';

export const App = () => {
  const [date, setDate] = useState(new Date(1598051730000));
  const [mode, setMode] = useState('date');
  const [show, setShow] = useState(false);

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

  const showMode = (currentMode) => {
    setShow(true);
    setMode(currentMode);
  };

  const showDatepicker = () => {
    showMode('date');
  };

  const showTimepicker = () => {
    showMode('time');
  };

  return (
    <View>
      <View>
        <Button onPress={showDatepicker} title="Show date picker!" />
      </View>
      <View>
        <Button onPress={showTimepicker} title="Show time picker!" />
      </View>
      {show && (
        <DateTimePicker
          testID="dateTimePicker"
          value={date}
          mode={mode}
          is24Hour={true}
          display="default"
          onChange={onChange}
        />
      )}
    </View>
  );
};
于 2021-07-02T04:04:35.420 回答