如何使用多个 React Native DateTimePicker
How to use multiple React Native DateTimePicker
我是react-native的新手。我必须创建一个具有多个日期时间选择器的表单。我怎样才能做到这一点。目前我的代码很乱,我想简化它。现在,我只是为每个日期时间选择器创建多个变量。这使我的代码更长且可重复。所以我真的希望有人能帮助我。谢谢。
constructor(props) {
super(props);
this.state = {
startbid: new Date(),
startbidMode: 'date',
startbidShow: false,
endbid: new Date(),
endbidMode: 'date',
endbidShow: false,
startservice: new Date(),
startserviceMode: 'date',
startserviceShow: false,
};
}
setStartbidDate = (event, startbid) => {
startbid = startbid || this.state.startbid;
this.setState({
startbidShow: Platform.OS === 'ios' ? true : false,
startbid,
});
}
setEndbidDate = (event, endbid) => {
endbid = endbid || this.state.endbid;
this.setState({
endbidShow: Platform.OS === 'ios' ? true : false,
endbid,
});
}
setStartserviceDate = (event, startservice) => {
startservice = startservice || this.state.startservice;
this.setState({
startserviceShow: Platform.OS === 'ios' ? true : false,
startservice,
});
}
show1 = startbidMode => {
this.setState({
startbidShow: true,
startbidMode,
});
}
show2 = endbidMode => {
this.setState({
endbidShow: true,
endbidMode,
});
}
show3 = startserviceMode => {
this.setState({
startserviceShow: true,
startserviceMode,
});
}
datepicker1 = () => {
this.show1('date');
}
datepicker2 = () => {
this.show2('date');
}
datepicker3 = () => {
this.show3('date');
}
这是我的表单代码。
<Form >
<Label style={styles.labelForm}>Start Bid</Label>
<Item rounded style={styles.inputs}>
<TouchableOpacity onPress={this.datepicker1} style={{flexDirection:"row", alignItems:'center'}}>
<Thumbnail source={require('../assets/images/icons/date.png')} style={styles.icons}/>
<Text style={{paddingHorizontal:10}}>{startbid.getDate() + '-' + (startbid.getMonth() + 1) + '-' + startbid.getFullYear()}</Text>
</TouchableOpacity>
{ startbidShow &&
<DateTimePicker
value={startbid}
mode={startbidMode}
display="default"
onChange={this.setStartbidDate}
/>
}
</Item>
<Label style={styles.labelForm}>End Bid</Label>
<Item rounded style={styles.inputs}>
<TouchableOpacity onPress={this.datepicker2} style={{flexDirection:"row", alignItems:'center'}}>
<Thumbnail source={require('../assets/images/icons/date.png')} style={styles.icons}/>
<Text style={{paddingHorizontal:10}}>{endbid.getDate() + '-' + (endbid.getMonth() + 1) + '-' + endbid.getFullYear()}</Text>
</TouchableOpacity>
{ endbidShow &&
<DateTimePicker
value={endbid}
mode={endbidMode}
display="default"
onChange={this.setEndbidDate}
/>
}
</Item>
<Label style={styles.labelForm}>Start Service</Label>
<Item rounded style={styles.inputs}>
<TouchableOpacity onPress={this.datepicker3} style={{flexDirection:"row", alignItems:'center'}}>
<Thumbnail source={require('../assets/images/icons/date.png')} style={styles.icons}/>
<Text style={{paddingHorizontal:10}}>{startservice.getDate() + '-' + (startservice.getMonth() + 1) + '-' + startservice.getFullYear()}</Text>
</TouchableOpacity>
{ startserviceShow &&
<DateTimePicker
value={startservice}
mode={startserviceMode}
display="default"
onChange={this.setStartserviceDate}
/>
}
</Item>
<View style={{paddingBottom:30}}>
<Button block
onPress={this.onClickSubmitButton}>
<Text>Submit</Text>
</Button>
</View>
</Form>
有什么方法可以使代码更简洁、代码更少?
我通过我的钩子做到了。我通过函数调用react组件
import React, { useState } from 'react'
import { View, Text, StyleSheet, Button, TextInput, Picker } from 'react-native'
import DateTimePicker from '@react-native-community/datetimepicker'
function useInput() {
const [date, setDate] = useState(new Date());
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const showMode = (currentMode) => {
setShow(true);
setMode(currentMode);
};
const showDatepicker = () => {
showMode('date');
};
const onChange = (event, selectedDate) => {
const currentDate = selectedDate || date
setShow(Platform.OS === 'ios');
setDate(currentDate);
}
return {
date,
showDatepicker,
show,
mode,
onChange
}
}
export const MainScreen = ({ navigation }) => {
const input = useInput(new Date())
const input2 = useInput(new Date())
return (
<View >
<Button
onPress={input.showDatepicker}
title={input.date.toLocaleDateString()} />
{input.show && (
<DateTimePicker
testID="dateTimePicker1"
value={input.date}
mode={input.mode}
is24Hour={true}
display="default"
onChange={input.onChange}
/>
)}
<Button
onPress={input2.showDatepicker}
title={input2.date.toLocaleDateString()} />
{input2.show && (
<DateTimePicker
testID="dateTimePicker2"
value={input2.date}
mode={input2.mode}
is24Hour={true}
display="default"
onChange={input2.onChange}
/>
)}
)
}
对于 class 组件中的多个日期时间选择器
import { differenceInDays, parseISO } from "date-fns";
import DateTimePicker from "@react-native-community/datetimepicker";
import { Overlay } from "react-native-elements";
class App extends Component {
constructor(props) {
super();
this.state = { rentStartDate: new Date(),
rentEndDate: new Date(),
startDate: "",
endDate: "",
visible: false,
visible2: false,}
this.onChangeStart = this.onChangeStart.bind(this);
this.onChangeEnd = this.onChangeEnd.bind(this);
}
toggleOverlay() {
this.setState({ visible: !this.state.visible });
}
toggleOverlay2() {
this.setState({ visible2: !this.state.visible2 });
}
onChangeStart(event, selectedDate) {
let currentDate = selectedDate || this.state.rentStartDate;
this.setState({
visible: Platform.OS === "ios",
rentStartDate: currentDate,
});
let mydate = JSON.stringify(currentDate)
.split("T")[0]
.trim()
.replace('"', "");
this.setState({ startDate: mydate });
}
onChangeEnd(event, Date) {
let currentDate2 = Date || this.state.rentEndDate;
let mydate1 = JSON.stringify(currentDate2)
.split("T")[0]
.trim()
.replace('"', "");
let day = differenceInDays(
parseISO(mydate1),
parseISO(this.state.startDate)
);
let calculate = Math.round(day * this.state.price.replace("$", ""));
this.setState({
endDate: mydate1,
visible2: !this.state.visible2,
PriceValue: calculate,
});
}
render() {
return( <View
style={{
flex: 1,
flexDirection: "row",
padding: 5,
justifyContent: "space-evenly",
}}
>
<View style={{ flex: 0.4 }}>
<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.toggleOverlay()}>
<Image
source={require("../images/calendar_ic_gray.png")}
style={{ height: 24, width: 24 }}
/>
</TouchableHighlight>
<Overlay
isVisible={this.state.visible}
onBackdropPress={() => {
this.toggleOverlay();
}}
>
<View style={{ flexDirection: "row", padding: 5 }}>
<Icon
name="ios-calendar"
size={26}
resizeMode={"contain"}
style={{
elevation: 5,
justifyContent: "flex-start",
alignSelf: "flex-start",
color: "rgba(0,0,0,0.7)",
}}
onPress={() => {
this.setState({ modalVisible: true });
}}
/>
<Text
style={{
alignItems: "center",
justifyContent: "center",
textAlign: "center",
color: "rgba(0,0,0,0.9)",
marginLeft: 15,
paddingTop: 5,
}}
>
Start Date
</Text>
</View>
<DateTimePicker
testID="dateTimePicker"
value={this.state.rentStartDate}
mode={"date"} //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 style={{ flex: 0.4 }}>
<Text style={{ textAlign: "center" }}>End 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.endDate}
</Text>
<TouchableHighlight onPress={() => this.toggleOverlay2()}>
<Image
source={require("../images/calendar_ic_gray.png")}
style={{ height: 24, width: 24 }}
/>
</TouchableHighlight>
<Overlay
isVisible={this.state.visible2}
onBackdropPress={() => {
this.combine_toggleOverlay2();
}}
>
<View style={{ flexDirection: "row", padding: 5 }}>
<Icon
name="ios-calendar"
size={26}
resizeMode={"contain"}
style={{
elevation: 5,
justifyContent: "flex-start",
alignSelf: "flex-start",
color: "rgba(0,0,0,0.7)",
}}
onPress={() => {
this.setState({ modalVisible: true });
}}
/>
<Text
style={{
alignItems: "center",
justifyContent: "center",
textAlign: "center",
color: "rgba(0,0,0,0.9)",
marginLeft: 15,
paddingTop: 5,
}}
>
End Date
</Text>
</View>
<DateTimePicker
testID="dateTimePicker"
value={this.state.rentEndDate}
mode={"date"} //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.onChangeEnd}
style={{ width: 320, backgroundColor: "white" }}
/>
</Overlay>
</View>
</View>
</View>)
}
}
我是react-native的新手。我必须创建一个具有多个日期时间选择器的表单。我怎样才能做到这一点。目前我的代码很乱,我想简化它。现在,我只是为每个日期时间选择器创建多个变量。这使我的代码更长且可重复。所以我真的希望有人能帮助我。谢谢。
constructor(props) {
super(props);
this.state = {
startbid: new Date(),
startbidMode: 'date',
startbidShow: false,
endbid: new Date(),
endbidMode: 'date',
endbidShow: false,
startservice: new Date(),
startserviceMode: 'date',
startserviceShow: false,
};
}
setStartbidDate = (event, startbid) => {
startbid = startbid || this.state.startbid;
this.setState({
startbidShow: Platform.OS === 'ios' ? true : false,
startbid,
});
}
setEndbidDate = (event, endbid) => {
endbid = endbid || this.state.endbid;
this.setState({
endbidShow: Platform.OS === 'ios' ? true : false,
endbid,
});
}
setStartserviceDate = (event, startservice) => {
startservice = startservice || this.state.startservice;
this.setState({
startserviceShow: Platform.OS === 'ios' ? true : false,
startservice,
});
}
show1 = startbidMode => {
this.setState({
startbidShow: true,
startbidMode,
});
}
show2 = endbidMode => {
this.setState({
endbidShow: true,
endbidMode,
});
}
show3 = startserviceMode => {
this.setState({
startserviceShow: true,
startserviceMode,
});
}
datepicker1 = () => {
this.show1('date');
}
datepicker2 = () => {
this.show2('date');
}
datepicker3 = () => {
this.show3('date');
}
这是我的表单代码。
<Form >
<Label style={styles.labelForm}>Start Bid</Label>
<Item rounded style={styles.inputs}>
<TouchableOpacity onPress={this.datepicker1} style={{flexDirection:"row", alignItems:'center'}}>
<Thumbnail source={require('../assets/images/icons/date.png')} style={styles.icons}/>
<Text style={{paddingHorizontal:10}}>{startbid.getDate() + '-' + (startbid.getMonth() + 1) + '-' + startbid.getFullYear()}</Text>
</TouchableOpacity>
{ startbidShow &&
<DateTimePicker
value={startbid}
mode={startbidMode}
display="default"
onChange={this.setStartbidDate}
/>
}
</Item>
<Label style={styles.labelForm}>End Bid</Label>
<Item rounded style={styles.inputs}>
<TouchableOpacity onPress={this.datepicker2} style={{flexDirection:"row", alignItems:'center'}}>
<Thumbnail source={require('../assets/images/icons/date.png')} style={styles.icons}/>
<Text style={{paddingHorizontal:10}}>{endbid.getDate() + '-' + (endbid.getMonth() + 1) + '-' + endbid.getFullYear()}</Text>
</TouchableOpacity>
{ endbidShow &&
<DateTimePicker
value={endbid}
mode={endbidMode}
display="default"
onChange={this.setEndbidDate}
/>
}
</Item>
<Label style={styles.labelForm}>Start Service</Label>
<Item rounded style={styles.inputs}>
<TouchableOpacity onPress={this.datepicker3} style={{flexDirection:"row", alignItems:'center'}}>
<Thumbnail source={require('../assets/images/icons/date.png')} style={styles.icons}/>
<Text style={{paddingHorizontal:10}}>{startservice.getDate() + '-' + (startservice.getMonth() + 1) + '-' + startservice.getFullYear()}</Text>
</TouchableOpacity>
{ startserviceShow &&
<DateTimePicker
value={startservice}
mode={startserviceMode}
display="default"
onChange={this.setStartserviceDate}
/>
}
</Item>
<View style={{paddingBottom:30}}>
<Button block
onPress={this.onClickSubmitButton}>
<Text>Submit</Text>
</Button>
</View>
</Form>
有什么方法可以使代码更简洁、代码更少?
我通过我的钩子做到了。我通过函数调用react组件
import React, { useState } from 'react'
import { View, Text, StyleSheet, Button, TextInput, Picker } from 'react-native'
import DateTimePicker from '@react-native-community/datetimepicker'
function useInput() {
const [date, setDate] = useState(new Date());
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const showMode = (currentMode) => {
setShow(true);
setMode(currentMode);
};
const showDatepicker = () => {
showMode('date');
};
const onChange = (event, selectedDate) => {
const currentDate = selectedDate || date
setShow(Platform.OS === 'ios');
setDate(currentDate);
}
return {
date,
showDatepicker,
show,
mode,
onChange
}
}
export const MainScreen = ({ navigation }) => {
const input = useInput(new Date())
const input2 = useInput(new Date())
return (
<View >
<Button
onPress={input.showDatepicker}
title={input.date.toLocaleDateString()} />
{input.show && (
<DateTimePicker
testID="dateTimePicker1"
value={input.date}
mode={input.mode}
is24Hour={true}
display="default"
onChange={input.onChange}
/>
)}
<Button
onPress={input2.showDatepicker}
title={input2.date.toLocaleDateString()} />
{input2.show && (
<DateTimePicker
testID="dateTimePicker2"
value={input2.date}
mode={input2.mode}
is24Hour={true}
display="default"
onChange={input2.onChange}
/>
)}
)
}
对于 class 组件中的多个日期时间选择器
import { differenceInDays, parseISO } from "date-fns";
import DateTimePicker from "@react-native-community/datetimepicker";
import { Overlay } from "react-native-elements";
class App extends Component {
constructor(props) {
super();
this.state = { rentStartDate: new Date(),
rentEndDate: new Date(),
startDate: "",
endDate: "",
visible: false,
visible2: false,}
this.onChangeStart = this.onChangeStart.bind(this);
this.onChangeEnd = this.onChangeEnd.bind(this);
}
toggleOverlay() {
this.setState({ visible: !this.state.visible });
}
toggleOverlay2() {
this.setState({ visible2: !this.state.visible2 });
}
onChangeStart(event, selectedDate) {
let currentDate = selectedDate || this.state.rentStartDate;
this.setState({
visible: Platform.OS === "ios",
rentStartDate: currentDate,
});
let mydate = JSON.stringify(currentDate)
.split("T")[0]
.trim()
.replace('"', "");
this.setState({ startDate: mydate });
}
onChangeEnd(event, Date) {
let currentDate2 = Date || this.state.rentEndDate;
let mydate1 = JSON.stringify(currentDate2)
.split("T")[0]
.trim()
.replace('"', "");
let day = differenceInDays(
parseISO(mydate1),
parseISO(this.state.startDate)
);
let calculate = Math.round(day * this.state.price.replace("$", ""));
this.setState({
endDate: mydate1,
visible2: !this.state.visible2,
PriceValue: calculate,
});
}
render() {
return( <View
style={{
flex: 1,
flexDirection: "row",
padding: 5,
justifyContent: "space-evenly",
}}
>
<View style={{ flex: 0.4 }}>
<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.toggleOverlay()}>
<Image
source={require("../images/calendar_ic_gray.png")}
style={{ height: 24, width: 24 }}
/>
</TouchableHighlight>
<Overlay
isVisible={this.state.visible}
onBackdropPress={() => {
this.toggleOverlay();
}}
>
<View style={{ flexDirection: "row", padding: 5 }}>
<Icon
name="ios-calendar"
size={26}
resizeMode={"contain"}
style={{
elevation: 5,
justifyContent: "flex-start",
alignSelf: "flex-start",
color: "rgba(0,0,0,0.7)",
}}
onPress={() => {
this.setState({ modalVisible: true });
}}
/>
<Text
style={{
alignItems: "center",
justifyContent: "center",
textAlign: "center",
color: "rgba(0,0,0,0.9)",
marginLeft: 15,
paddingTop: 5,
}}
>
Start Date
</Text>
</View>
<DateTimePicker
testID="dateTimePicker"
value={this.state.rentStartDate}
mode={"date"} //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 style={{ flex: 0.4 }}>
<Text style={{ textAlign: "center" }}>End 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.endDate}
</Text>
<TouchableHighlight onPress={() => this.toggleOverlay2()}>
<Image
source={require("../images/calendar_ic_gray.png")}
style={{ height: 24, width: 24 }}
/>
</TouchableHighlight>
<Overlay
isVisible={this.state.visible2}
onBackdropPress={() => {
this.combine_toggleOverlay2();
}}
>
<View style={{ flexDirection: "row", padding: 5 }}>
<Icon
name="ios-calendar"
size={26}
resizeMode={"contain"}
style={{
elevation: 5,
justifyContent: "flex-start",
alignSelf: "flex-start",
color: "rgba(0,0,0,0.7)",
}}
onPress={() => {
this.setState({ modalVisible: true });
}}
/>
<Text
style={{
alignItems: "center",
justifyContent: "center",
textAlign: "center",
color: "rgba(0,0,0,0.9)",
marginLeft: 15,
paddingTop: 5,
}}
>
End Date
</Text>
</View>
<DateTimePicker
testID="dateTimePicker"
value={this.state.rentEndDate}
mode={"date"} //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.onChangeEnd}
style={{ width: 320, backgroundColor: "white" }}
/>
</Overlay>
</View>
</View>
</View>)
}
}