属性“click”在类型“never”上不存在。TS2339

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 无法从您稍后在代码中使用引用的位置推断出引用的类型,您必须告诉它引用的类型:

\n
const 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添加到类型参数中,因此您不必使用,但如果您这样做并且得到相同的结果也很好。)nullnull<HTMLDivElement | null>

\n