首页 > 解决方案 > 当 DatePicker 的 onDateChange 时 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;

标签: react-native

解决方案


您不能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;

推荐阅读