nov*_*imo 15 javascript typescript reactjs react-hooks
根据有关 TypeScript 此类错误的其他类似问题(关于问题#44147937和#40796374),我发现分配null
创建状态或引用会导致此问题:
Property ... does not exist on type 'never'
如何在这个示例组件中处理这个问题?
const FooComponent: FunctionComponent<FooInterface> = () => {
const myRef = useRef(null)
const handleClickOnButton = () => myRef?.current?.click();
return (
<div>
<div ref={myRef} />
<button onClick={handleClickOnButton} />
</div>
}
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 49
TypeScript 无法从您稍后在代码中使用引用的位置推断出引用的类型,您必须告诉它引用的类型:
\nconst ref = useRef<HTMLDivElement>(null);\n// \xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92^^^^^^^^^^^^^^^^\n
Run Code Online (Sandbox Code Playgroud)\n(如果您用作初始值设定项,则将类型useRef
添加到类型参数中,因此您不必使用,但如果您这样做并且得到相同的结果也很好。)null
null
<HTMLDivElement | null>
归档时间: |
|
查看次数: |
22763 次 |
最近记录: |