简体   繁体   English

如何在 React Native 的 Textinput 字段中打开和设置日期 - datepicker

[英]how to open and set date in Textinput field in react native - datepicker

This is what I am trying.这就是我正在尝试的。 On focus of TextInput datepicker does get open but after selecting date it is not getting populated in TextInput field.在 TextInput 的焦点上,日期选择器确实打开了,但在选择日期后,它没有被填充到 TextInput 字段中。 Where I am making mistake?我在哪里犯错?

<TouchableOpacity>
  <TextInput style={styles.textinputstyle} onFocus={()=>{setOpen(true)}} />
</TouchableOpacity>
<DatePicker modal mode="date" dateFormat="MM-DD-YYYY" open={open} date={date} onConfirm={date=> { setOpen(false) setDate(date) }} onCancel={() => { setOpen(false) }} />

set editable = false in TextInput在 TextInput 中设置 editable = false

 const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
  const [birthDate, setBirthDate] = useState('');

  const showDatePicker = () => {
    setDatePickerVisibility(true);
  };

  const hideDatePicker = () => {
    setDatePickerVisibility(false);
  };

  const handleConfirm = date => {
    setBirthDate(date);
    hideDatePicker();
  };

 <TouchableOpacity onPress={showDatePicker}>
          <TextInput
            numberOfLines={1}
            editable={false}
            placeholder="Choose Your Date of Birth"
            value={moment(birthDate).format('DD MMMM, YYYY')}
            style={{
              fontSize: 16,
              paddingVertical: 10,
              color: 'black',
            }}
          />
          <DateTimePickerModal
            isVisible={isDatePickerVisible}
            maximumDate={new Date(moment().add(-1, 'days'))}
            mode="date"
            onChange={date => setBirthDate(date)}
            value={handleConfirm}
            onConfirm={handleConfirm}
            onCancel={hideDatePicker}
          />
        </TouchableOpacity>
import React, { useState,useEffect } from 'react';
import {
    Text,
    View,
    StyleSheet,
    TextInput,
    SafeAreaView,
    ScrollView,
    FlatList,
    TouchableOpacity,
} from 'react-native';
import RNCalendarEvents from 'react-native-calendar-events';
import DatePicker from 'react-native-date-picker';
import { openDatabase } from 'react-native-sqlite-storage';


const db = openDatabase({
    name: "calendar",
});


const Main = ({ navigation }) => {
    const [eventTitle, setEventTile] = React.useState('');
    const [eventLocation, setEventLocation] = React.useState('');
    const [date, setDate] = React.useState(new Date());
    const [open, setOpen] = React.useState(false);
    const [dateValue, setdateValue] = React.useState('');
    const [name, setName] = useState();
    const [location, setLocation] = useState();
    const [time, setTime] = useState();
    const [id, setId] = useState();
    const [categories, setCategories] = useState([]);

    const addCategory = () => {
        //if (!category||!adddescription||!adddata)
        if (name.length == 0 || location.length == 0 || time.length == 0) {
            alert("Enter category");
            return false;
        }
    useEffect(async () => {
        //let interval = setInterval(() => setTime(1), 1000)

        await createTables();
        await getCategories();
        // return () => {
        //     clearInterval(interval);
        // }
    }, []);

    React.useEffect(() => {
        RNCalendarEvents.requestPermissions()
            .then(res => {
                console.log('Premission Response', res);
            })
            .catch(error => {
                console.log(error);
            });
    }, []);

    const createEvent = () => {
        const newDate = new Date(date);
        newDate.setHours(newDate.getHours() + 2);

        RNCalendarEvents.saveEvent(eventTitle, {
            calendarId: '3',
            startDate: date.toISOString(),
            endDate: newDate.toISOString(),
            location: eventLocation
        }).then((value) => {
            console.log('Event Id--->', value);
            setId(value)
            console.log("Event Data-->", name);
            console.log("Event Data-->", location);
            console.log("Event time-->", time);


        }).catch((error) => {
            console.log(' Did Not work Threw an error --->', error)
        })

    }

    function submit() {
        const newDate = new Date(date);
        newDate.setHours(newDate.getHours() + 2);

        RNCalendarEvents.saveEvent(eventTitle, {
            calendarId: '3',
            startDate: date.toISOString(),
            endDate: newDate.toISOString(),
            location: eventLocation
        }).then((value) => {
            console.log('Event Id--->', value);
            setId(value)
            console.log("Event Data-->", name);
            console.log("Event Data-->", location);
            console.log("Event time-->", time);
            addCategory();
        //    navigation.navigate("RootScreen")

        }).catch((error) => {
            console.log(' Did Not work Threw an error --->', error)
        })
    }


    const renderItem = ({ item }) => (
        <Text style={styles.title}>{name}</Text>
    );

    return (
        <View style={styles.container}>
            <ScrollView>

                <View style={styles.mainContainer}>
                    <View style={styles.singleElement}>
                        <View style={styles.dateInputContainer}>
                            <TextInput value={dateValue} style={styles.dateInput} />

                            <TouchableOpacity
                                style={styles.dateIcon}
                                onPress={() => setOpen(true)}>
                                <Text> SELECT DATA/TIME </Text>
                            </TouchableOpacity>

                            <DatePicker
                                modal
                                open={open}
                                date={date}
                                onConfirm={date => {
                                    var currentdate = new Date(date);
                                    var datetime =
                                        +currentdate.getDate() +
                                        '/' +
                                        (currentdate.getMonth() + 1) +
                                        '/' +
                                        currentdate.getFullYear() +
                                        ' - ' +
                                        currentdate.getHours() +
                                        ':' +
                                        currentdate.getMinutes();

                                    setOpen(false);
                                    setDate(date);
                                    setTime(date);
                                    setdateValue(datetime.toString());
                                }}
                                minimumDate={new Date()}
                                onCancel={() => {
                                    setOpen(false);
                                }}
                            />
                        </View>
                    </View>
                </View>

                <TouchableOpacity
                    style={{
                        flex: 2,
                        padding: 25,
                        height: 72,
                        justifyContent: 'center',
                        alignSelf: 'center',
                    }}
                    onPress={() => submit()}

                >
                    <Text> Save Event </Text>
                </TouchableOpacity>

            </ScrollView>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f4f4fc',
        marginTop: 50,
    },
    mainContainer: {
        display: 'flex',
        flexDirection: 'row',
        padding: 10,
    },

    singleElement: {
        display: 'flex',
        flex: 4,
        flexDirection: 'column',
    },

    textInputContainer: {
        display: 'flex',
        flexDirection: 'column',
        padding: 15,
        backgroundColor: '#fff',
        borderRadius: 15,
        marginBottom: 1,
    },

    dateInputContainer: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#fff',
        padding: 15,
        borderRadius: 15,
        marginBottom: 1,
        margin: 2,
    },

    dateIcon: {
        padding: 10,
    },
});

export default Main;

This will help you这会帮助你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 TextInput 反应原生 DatePicker - React Native DatePicker with TextInput 如何在不使用值的情况下设置 TextInput 字段 - React Native - How to Set TextInput Field Without Using Value - React Native 如何在React Native中将TextInput的宽度设置为100%? - How to set 100% width to TextInput in React Native? 如何在React Native中在TextInput上设置焦点侦听器 - How to set focus listener on TextInput in react native 如何在 React Native 中设置键盘上方的 TextInput - How to set TextInput above of the keyboard in React Native 如何在react native中设置textInput中的值 - How to set value in textInput in react native 如果日期低于指定日期,则在 textinput 上设置错误反应本机 - Set error on textinput if date is below a specified date react native react native输入输入框时如何在键盘上方设置文本输入框 - How to set the textinput box above the Keyboard while entering the input field in react native 如何在不使用键盘onLongPress的情况下在TextInput上打开上下文菜单(React Native) - How to open context menu without keyboard onLongPress on TextInput (React Native) 如何在 React Native 中使用 TextInput 打开表情符号键盘,而不是字母表 - How to open emoji keyboard, instead of alphabets using TextInput in React Native
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM