【发布时间】:2022-01-01 12:48:33
【问题描述】:
我正在尝试对输入元素使用 ref,然后使用 inputRef.current.value 获取其值
但我在inputRef.current 收到错误Object is possibly 'null'.ts(2531)。
我尝试了几种不同的解决方案,但还没有成功。任何帮助表示赞赏。
interface RefObject<T> {
readonly current: T | null
}
const Uncontrolled: React.FC = () => {
// const inputRef = useRef< HTMLInputElement | null> (null);
const inputRef:RefObject<HTMLInputElement> = useRef< HTMLInputElement | null> (null);
function alertValue() {
alert(inputRef.current.value); //Object is possibly 'null', under inputRef.current
}
return (
<div>
<p> Uncontrolled components do not have state data</p>
<input type="text" ref={inputRef} />
<button onClick={alertValue}>Click Me</button>
</div>
)
}
我的解决方案来自:
useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement>
【问题讨论】:
标签: reactjs typescript