简体   繁体   English

React TypeScript:正确的 onChange 类型

[英]React TypeScript: Correct Types for onChange

What are the correct types for target: { value: any, name: any } ? target: { value: any, name: any }的正确类型是什么target: { value: any, name: any } The error I get is Duplicate identifier 'any'.我得到的错误是Duplicate identifier 'any'. I also get the error Binding element 'any' implicitly has an 'any' type.我还收到错误Binding element 'any' implicitly has an 'any' type. And why does value give the error 'Cannot find name 'value'?'为什么value给出错误“无法找到名称 'value'?”

I have a 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}
/>

event from onChange should be ChangeEvent<HTMLInputElement>来自onChange event应该是ChangeEvent<HTMLInputElement>

So, you must do this:所以,你必须这样做:

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM