TypeError: Cannot read property 'name' of undefined in ReactJS form field

TypeError: Cannot read property 'name' of undefined in ReactJS form field

我正在尝试使用 [event.target.name]:event.target.value

绑定我的数组值

但是我得到这个错误:

TypeError: Cannot read property 'name' of undefined.

我的代码如下所示:

数组

 const [data, setData] = useState({
        email: '', first_name: '', last_name: '', occupation: '',
        farm_description: '', farm_name: '', username:'',
        registration_status: false, capacity: '50-100',
        location: '', major_product: '', phone_num: ''
    });

更改处理程序:

const handleChange = (event) => {
        setData({
            ...data,
            [event.target.name]: event.target.value,
        });
    };

字段:

  <input type="text" placeholder="John" className="border-remove" 
name="first_name" type="text" onChange={props.handleChange('first_name')}/>

您在渲染时立即调用 handleChange,而不是传递要添加为侦听器的函数。当函数仅接受 事件 的参数时,您还向其传递了一个 first_name 参数。改用:

onChange={props.handleChange}

您传递的是 first_name 而不是事件,请将代码更改为:

<input type="text" placeholder="John" className="border-remove" name="first_name" type="text" onChange={props.handleChange}/>

更改这行代码

onChange={props.handleChange('first_name')}

onChange={props.handleChange}

在您的代码中,您没有将事件传递给函数,因此它是未定义的。

[OR] -- 将事件显式传递给方法。

onChange={(e) => props.handleChange(e)}

输入的onChange函数,如果<input />和handle change函数在同一个组件中,则不需要调用as props.handleChange。你可以调用 handleChange

onChange={props.handleChange}