有没有办法从react-native-datetimepicker以编程方式打开/关闭日期选择器?我的用例是创建一个基于TouchableOpacity的组件,当按下时打开DatePicker(比微小的日期选择器具有更大的表面积)。RNDateTimePicker似乎不接受ref,也没有隐藏/显示的API。非常感谢。
react-native-datetimepicker
TouchableOpacity
RNDateTimePicker
ref
6ss1mwsb1#
文档页面中有一个演示。控制显示状态以隐藏或显示日期选择器。
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> ); };
njthzxwz2#
使用react-native-datetimepicker页面上给出的示例,我可以使用这里的一个小技巧让它满足我的需求;
useEffect(() => { if (show) return; setShow(true); }, [show])
ui7jx7zq3#
国家的魔力来了。试着这样做,
import React, { useState } from 'react'; import { TouchableOpacity, Text } from 'react-native'; import DateTimePicker from 'react-native-datetimepicker'; const CustomDateTimePicker = () => { const [showPicker, setShowPicker] = useState(false); const [selectedDate, setSelectedDate] = useState(new Date()); const handlePickerOpen = () => { setShowPicker(true); }; const handlePickerClose = () => { setShowPicker(false); }; const handleDateChange = (event, date) => { if (date !== undefined) { setSelectedDate(date); // Do something with the selected date } setShowPicker(false); }; return ( <> <TouchableOpacity onPress={handlePickerOpen}> <Text>Open Date Picker</Text> </TouchableOpacity> {showPicker && ( <DateTimePicker value={selectedDate} mode="date" onChange={handleDateChange} /> )} </> ); }; export default CustomDateTimePicker;
通过使用状态变量,我们可以根据需要将状态设置为true或false。
3条答案
按热度按时间6ss1mwsb1#
文档页面中有一个演示。控制显示状态以隐藏或显示日期选择器。
njthzxwz2#
使用react-native-datetimepicker页面上给出的示例,我可以使用这里的一个小技巧让它满足我的需求;
ui7jx7zq3#
国家的魔力来了。试着这样做,
通过使用状态变量,我们可以根据需要将状态设置为true或false。