React TypeScript:onChange 的正确类型

Bil*_*ill 8 typescript reactjs

正确的类型是什么target: { value: any, name: any }?我得到的错误是Duplicate identifier 'any'.我也得到了错误Binding element 'any' implicitly has an 'any' type.为什么会value给出错误“找不到名称‘值’?”

我这里有一个代码沙箱


const [state, setState] = useState({
    fullName: '',
});

const { fullName } = state;

const onChange = ({ target: { value: any, name: any } }) => {
    setState((prev) => ({
        ...prev,
        [name] : value, // <= 'Cannot find name 'value'
    }));
};

...

<input
  type='text'
  placeholder='Full name'
  name='fullName'
  value={fullName}
  onChange={onChange}
/>
Run Code Online (Sandbox Code Playgroud)

svl*_*ccc 18

eventonChange应该是ChangeEvent<HTMLInputElement>

所以,你必须这样做:

const [fullName, setFullName] = useState('');

...

const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    setFullName(event.currentTarget.value);
};

...

<input
  type='text'
  placeholder='Full name'
  name='fullName'
  value={fullName}
  onChange={onChange}
/>
Run Code Online (Sandbox Code Playgroud)

  • 我应该像“import React, { ChangeEvent, useState } from 'react';”一样导入ChangeEvent吗? (4认同)