React TypeScript:onChange的正确类型

时间:2019-12-02 10:42:14

标签: reactjs typescript

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

我有一个code sandbox here


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}
/>

1 个答案:

答案 0 :(得分:1)

event中的

onChange应该是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}
/>