Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
991 views
in Technique[技术] by (71.8m points)

reactjs - TypeError: Cannot destructure property 'name' of 'e.target' as it is undefined. with DatePicker in React Hooks

I will be grateful for any help. Unable to assign value from DatePicker field. All other input fields work fine. Why can't I assign a value to a variable in a DatePicker field?

import React, { useState } from 'react';
import useForm from './useForm';
import validate from './validateInfo';
import './Form.css';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

const FormInput = ({ submitForm }) => {
    const { handleChange, values, handleSubmit, errors } = useForm(submitForm, validate);
    console.log(values);
    const [date, setDate] = useState(new Date());
    console.log(date)

    return (
        <div className="form-content-right">
            <form className="form" onSubmit={handleSubmit}>
                <h1>Neuen Fehler eingeben.
                </h1>
                <div className="form-inputs">
                    <div>
                        <label htmlFor="startDate"
                            className="form-label">
                            Datum
                    </label>
                            <DatePicker
                                id="startDate"
                                type="date"
                                name="startDate"
                                className="form-input"
                                value={date.toString()}
                                onChange={handleChange}
                            />
                    </div>

                  // ... some other input fields...
               
                <button className="form-input-btn"
                    type='submit'>
                    eingeben
                </button>
            </form>
        </div>
    )
}

export default FormInput;
question from:https://stackoverflow.com/questions/65889623/typeerror-cannot-destructure-property-name-of-e-target-as-it-is-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The onChange callback of the react-datepicker component seems to return the value directly without the event object.

Can you try something like that:

<DatePicker
  id="startDate"
  type="date"
  name="startDate"
  className="form-input"
  value={date.toString()}
  onChange={date => handleChange({ target: { value: date, name: 'startDate' } })}
/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...