React项目,使用的Typescript,UI库是antd。
在使用Input组件的时候,我想通过给使用useRef这个hook来获取Input的值,看代码:
import styles from './index.less';
import {Input,Button} from "antd";
import { useRef } from 'react';
export default (props: any) => {
const userRef = useRef<HTMLInputElement>();
const handleClick = () => {
console.log("userRef:",userRef.current?.value);
}
return (
<>
<Input type='text' ref={userRef} className={styles.input} />
<Button type='primary' onClick={handleClick}>提交</Button>
</>
);
};
可是这样的代码,在ts编译的时候,报异常信息了:
Input组件中在使用ref属性的时候,报了错。
这里报的是类型的错误,那我就在定义ref的时候,指定了一个类型:HTMLInputElement,如:
const userRef = useRef<HTMLInputElement | null>();
可是异常信息还是存在。
在有类型异常的情况下,我尝试看是不是可以获取到Input组件的值,但是结果只是undefined。
到这里,我就不知道在在Input组件使用useRef的时候,怎么定义类型了。
PS:使用原生input组件的时候,是正常的,可以通过ref的current属性获取到正常的值。
你使用的是
antd
的Input
,并不是HTMLInputElement