我如何在文本输入中显示从时间选择器中选择的时间?
Posted
技术标签:
【中文标题】我如何在文本输入中显示从时间选择器中选择的时间?【英文标题】:how can i display the selected time from a timepicker in a textinput react native 【发布时间】:2021-10-19 22:58:51 【问题描述】:我使用这个时间选择器我的目标是从选择器中选择一个时间并将其显示在我的文本输入中一切正常,直到我选择它不会显示的时间并给我一个文本输入值必须的错误是一个字符串谁能告诉我我做错了什么这是我到目前为止的代码
import React, useState from 'react';
import View, TextInput, Text, Platform, Button from 'react-native';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
const AttendanceMain = () =>
const [showPicker, setShowPicker] = useState(false);
const [selectedTime, setSelectedTime] = useState('');
const showTimePicker = () =>
setShowPicker(true);
;
const hideTimePicker = () =>
setShowPicker(false);
;
const handleConfirm = (time) =>
setSelectedTime(time);
hideTimePicker();
;
return (
<View>
<Text>From:</Text>
<TextInput
placeholder="00:00"
keyboardType="numeric"
onFocus=showTimePicker
value=selectedTime
onChange=handleConfirm
/>
<Text>To:</Text>
<TextInput
placeholder="00:00"
keyboardType="numeric"
onFocus=showTimePicker
value=selectedTime
onChange=handleConfirm
/>
<DateTimePickerModal
isVisible=showPicker
mode="time"
is24Hour=true
onConfirm=handleConfirm
onCancel=hideTimePicker
/>
</View>
);
;
export default AttendanceMain;
【问题讨论】:
【参考方案1】:你为什么不用react-native-datetimepicker/datetimepicker
Working Example
并像这样实现它
import React, useState from 'react';
import View, Button, Platform, Text, TextInput from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
const App = () =>
const [From, setFrom] = useState(new Date());
const [To, setTo] = useState(new Date());
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const [currentSetting, setcurrentSetting] = useState('from');
const onChange = (event, selectedDate) =>
if (currentSetting === 'from')
const currentDate = selectedDate || From;
setShow(Platform.OS === 'ios');
setFrom(currentDate);
else
const currentDate = selectedDate || To;
setShow(Platform.OS === 'ios');
setTo(currentDate);
;
const showTimepicker = (current) =>
setShow(true);
setcurrentSetting(current);
;
return (
<View style= flex: 1, justifyContent: 'center', alignItems: 'center' >
<View>
<Text>From:</Text>
<TextInput
placeholder="00:00"
keyboardType="numeric"
onFocus=() => showTimepicker('from')
value=From.toLocaleTimeString()
/>
<Text>To:</Text>
<TextInput
placeholder="00:00"
keyboardType="numeric"
onFocus=() => showTimepicker('to')
value=To.toLocaleTimeString()
/>
</View>
show && (
<DateTimePicker
testID="dateTimePicker"
value=From
mode='time'
is24Hour=true
display="default"
onChange=onChange
/>
)
</View>
);
;
export default App;
【讨论】:
以上是关于我如何在文本输入中显示从时间选择器中选择的时间?的主要内容,如果未能解决你的问题,请参考以下文章