react-native - 当 DatePicker 的 onDateChange 时 setState 未定义
问题描述
- 我的目的是拥有一个 Datepicker 并在更改日期时需要使用选定的日期进行设置。但我无法使用 setState 函数。如果我使用它,setState 是未定义的。任何人都可以帮助调试此错误。
提前致谢。*
import React, {useState} from 'react';
import {View,Text,StyleSheet,DatePickerIOS} from 'react-native';
import DatePicker from 'react-native-datepicker';
import { DateInput } from 'react-native-date-input';
const AttendanceScreen = props =>{
this.state = {date:"06 Jul 2020"}
return(
<View>
{/* <Text style={styles.selectDate}>Select Date</Text> */}
<DatePicker
style={{width: 200}}
date={this.state.date}
mode="date"
placeholder="select date"
format="DD MMM YYYY"
minDate="01 Jan 2020"
maxDate="30 Dec 2021"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
customStyles={{
dateIcon: {
position: 'absolute',
left: 0,
top: 4,
marginLeft: 0
},
dateInput: {
marginLeft: 36
}
// ... You can check the source to find the other keys.
}}
onDateChange={(date) => {this.setState({date: date})}}
/>
</View>
)
};
const styles = StyleSheet.create({
selectDate:{
fontFamily:'open-sans',
fontSize:20,
alignSelf:'center',
color:'red'
},
datebox:{
alignSelf:'center',
height:50,
width:500
}
});
export default AttendanceScreen;
解决方案
您不能this
在箭头函数中使用。更改this.state = {date:"06 Jul 2020"}
为
const [date,setDate] = useState("06 Jul 2020")
你也需要改变处理方式。
你的代码应该是这样的:
import React, { useState } from 'react';
import { View, Text, StyleSheet, DatePickerIOS } from 'react-native';
import DatePicker from 'react-native-datepicker';
import DateInput from 'react-native-date-input';
const AttendanceScreen = props => {
const [date, setDate] = useState("06 Jul 2020")
const handleDate = (e) => {
setDate(e.target.date)
}
return (
<View>
{/* <Text style={styles.selectDate}>Select Date</Text> */}
<DatePicker
style={{ width: 200 }}
date={date}
mode="date"
placeholder="select date"
format="DD MMM YYYY"
minDate="01 Jan 2020"
maxDate="30 Dec 2021"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
customStyles={{
dateIcon: {
position: 'absolute',
left: 0,
top: 4,
marginLeft: 0
},
dateInput: {
marginLeft: 36
}
// ... You can check the source to find the other keys.
}}
onDateChange={handleDate}
/>
</View>
)
};
export default AttendanceScreen;
推荐阅读
- node.js - 如何从nodejs中的ElasticSearch批量查询
- python - Pandas 在匹配列中加入具有不同间隔的数据帧
- javascript - 将变量从一个函数传递到另一个函数
- python - 有没有办法随机打乱 Python 字典中的键和值,但结果不能有任何原始键值对?
- javascript - 如何在更改原点的 chrome-extension 中使用 fetch?
- object - 在数组对象类中找不到方法的符号
- sql - 当一列为空时,使用 db2 中的另一列
- python - UTC 时间戳转换为日期时间返回意外日期
- node.js - 一种逐一检查集合中所有数据的有效方法(nodejs、mongoose)
- c - 如何将文件的内容存储到数组中 (C)