[英]Using react native date time picker twice gives an error?
我使用 expo 的日期時間選擇器,如果我只單擊一次它就可以正常工作。 如果我點擊它兩次,它會給我以下錯誤:
TypeError: value.getTime is not a function. (In 'value.getTime()', 'value.getTime' is undefined)
此錯誤位於:在 RNDateTimePicker 中(在 MyDateTimePicker.js:52)
這是我的日期時間選擇器:
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Image, Button, StyleSheet, TouchableOpacity } from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
import Moment from 'moment';
export default function MyDateTimePicker(props) {
console.log("my date time picker props: ", props);
const title = props.title;
const [date, setDate] = useState(new Date());
const [time, setTime] = useState(new Date());
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const [text, setText] = useState(Moment(date).format('DD MMM YYYY HH:mm'));
const onChange = (event, selectedValue) => {
setShow(Platform.OS === 'ios');
if (mode == 'date') {
const currentDate = selectedValue || new Date();
setDate(new Date(currentDate));
setMode('time');
setShow(Platform.OS !== 'ios'); // to show time
} else {
const currentTime = selectedValue || new Date();
setDate(date.setTime(currentTime.getTime()));
setShow(Platform.OS === 'ios'); // to hide back the picker
setMode('date'); // defaulting to date for next open
}
props.updateDate(date);
};
const showMode = (currentMode) => {
setShow(true);
setMode(currentMode);
};
const showDatepicker = () => {
console.log("show date picker");
showMode('date');
};
const showTimepicker = () => {
console.log("show time picker");
showMode('time');
};
return(
<View style={styles.viewStyle}>
<TouchableOpacity onPress={showDatepicker}>
<Text style={styles.inputStyle}>{text}</Text>
</TouchableOpacity>
{show && (
<DateTimePicker
value={date}
mode={mode}
is24Hour={true}
display="default"
onChange={onChange}
minimumDate={new Date()}
showTimeSelect
/>
)}
</View>
)
}
這就是我使用它的方式:
<MyDateTimePicker updateDate={(date) => this.handleDate(date)} />
在哪里
handleDate(date) {
this.setState({date: date});
}
同樣,如果我只單擊一次日期時間選擇器,一切正常,但如果我嘗試 select 第二個日期,它會中斷,我不明白為什么。
問題在這里:
setDate(date.setTime(currentTime.getTime()));
setTime
返回從 01.01.1970(從 javascript 開發人員的角度創建世界的時間)經過的秒數,但數據選擇器需要一個日期,而不是數字,因此它嘗試在一個數字上調用getTime
,這go 不是很好。
我不熟悉這個特定的數據選擇器,但如果您確定它在“時間”模式下會丟失日期部分,請嘗試
setDate(new Date(date.getTime()+currentTime.getTime()));
如果這讓你離未來太遠setDate(currentTime)
可能就足夠了(僅適用於“時間”模式,“日期”部分很好)
使用 react-native-datetimepicker 庫一段時間以來,我完全被同樣的錯誤所困擾。
它對我有用的方式是我以所需格式手動創建日期並將其傳遞給日期選擇器。 由於某種原因,使用 moment().toISOString() 對我不起作用,盡管格式與您更改日期或時間后日期選擇器的格式相同。
代碼大致如下:
const [customDate, setCustomDate] = useState(null);
useEffect(() => {
const year = new Date().getFullYear();
const month = new Date().getMonth();
const date = new Date().getDate();
const currentTime = new Date(year, month, date, 8, 11, 0);
setCustomDate(currentTime);
}, []);
const selectDate = (event, selectedDate) => {
const date = selectedDate || customDate;
setCustomDate(date);
};
<DateTimePicker mode="date" value={customDate} onChange={selectDate} />
class Productdetails extends Component {
constructor(props) {
super();
this.state = {
rentStartDate: new Date(),
startDate: "",
endDate: "",
mode: false,}
this.onChangeStart = this.onChangeStart.bind(this);
}
onChangeStart(event, selectedDate) {
let currentDate = selectedDate || this.state.rentStartDate;
this.setState({ show: Platform.OS === "ios", rentStartDate: currentDate });
let mydate = JSON.stringify(currentDate)
.split("T")[0]
.trim()
.replace('"', "");
this.setState({ startDate: mydate });
}
showMode(currentMode) {
this.setState({
show: true,
mode: currentMode,
});
}
return(<View style={{ flex: 1}}>
<Text style={{ textAlign: "center" }}>Start Date</Text>
<View
style={{
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 5,
height: 40,
borderRadius: 2,
color: "black",
borderColor: "rgba(38, 38, 38,0.8)",
borderWidth: 1,
backgroundColor: "white",
paddingEnd: 5,
}}
>
<Text
style={{
fontSize: 14,
paddingLeft: 5,
backgroundColor: "white",
color: "black",
}}
>
{this.state.startDate}
</Text>
<TouchableHighlight onPress={() => this.showMode("date")}>
<Image
source={require("../images/calender.png")}
style={{ height: 24, width: 24 }}
/>
</TouchableHighlight>
<Overlay
isVisible={this.state.show}
onBackdropPress={() => {
this.setState({ show: false });
}}
>
<DateTimePicker
testID="dateTimePicker"
value={this.state.rentStartDate}
mode={this.state.mode} //The enum of date, datetime and time
placeholder="select date"
format="DD-MM-YYYY"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
timeZoneOffsetInMinutes={undefined}
modalTransparent={false}
animationType={"fade"}
display="default"
onChange={this.onChangeStart}
style={{ width: 320, backgroundColor: "white" }}
/>
</Overlay>
</View>
<View></View>
</View>)
export default React.memo(Productdetails);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.