我想知道如何在react native中单击按钮时显示日期选择器。我尝试过各种解决方案仍然没有成功,任何帮助都会有所帮助。谢谢。
以下是我尝试过的
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
View,DatePicker
} from 'react-native';
Run Code Online (Sandbox Code Playgroud)
这是我的渲染方法
render(){
return(
<TouchableOpacity
onPress={() => this.datePicker.onPressDate()}>
<Text>
Hello Date
</Text>
</TouchableOpacity>
<DatePicker
style={{width: 200}}
ref={(picker) => { this.datePicker = picker; }}
date={this.state.date}
mode="date"
placeholder="Select date"
format="YYYY-MM-DD"
minDate="2016-05-01"
maxDate="2020-12-12"
confirmBtnText="OK"
cancelBtnText="Cancel"
onDateChange={(date) => {this.setState({date: date})}}
/>
);
}
Run Code Online (Sandbox Code Playgroud)
每当我运行时,我都会遇到以下错误, 在此处输入图片描述
您可以简单地标记是否渲染选择器组件并将其打开按。像这样的东西
render() {
return (
<View>
<TouchableOpacity
onPress={() => this.setState({ picker: !this.state.picker })}>
<Text>Hello Date</Text>
</TouchableOpacity>
{this.renderPicker()}
</View>
);
}
renderPicker() {
if (this.state.picker) {
return (
<DatePicker
style={{ width: 200 }}
ref={picker => {
this.datePicker = picker;
}}
date={this.state.date}
mode="date"
placeholder="Select date"
format="YYYY-MM-DD"
minDate="2016-05-01"
maxDate="2020-12-12"
confirmBtnText="OK"
cancelBtnText="Cancel"
onDateChange={date => {
this.setState({ date: date });
}}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我建议对日期选择器使用react-native-datepicker库。它将为您提供更多自定义选项,并且兼容 Android 和 iOS 两个平台。
以下是我在我的应用程序之一中使用的示例代码:-
<View style={{ backgroundColor: 'transparent', margin: 5 }}>
<DatePicker date={this.state.date} showIcon={false} placeholder="Birthday" mode="date" format="DD-MM-YYYY"
customStyles={{
dateInput: {
borderWidth: 0,
height: 50,
width: 170,
right: 30,
},
dateText: {
marginTop: 5,
color: 'white',
fontSize: 18,
},
placeholderText: {
marginTop: 5,
right: 10,
color: 'white',
fontSize: 18,
}
}
}
onDateChange={(date) => { this.setState({ date: date }) }} placeholderTextColor="white" underlineColorAndroid={'rgba(0,0,0,0)'} style={{ height: 50, width: 170, paddingLeft: 15, borderRadius: 4, backgroundColor: 'rgba(0,0,0,0.4)' }}></DatePicker>
</View>
Run Code Online (Sandbox Code Playgroud)
您可以在这里找到该库
| 归档时间: |
|
| 查看次数: |
6012 次 |
| 最近记录: |