【发布时间】:2019-10-16 03:11:07
【问题描述】:
我刚刚被运行时异常所困扰,因为我将 React ref 传递给了错误的组件。
我想知道 TypeScript 是否/如何将我的培根保存在这里?
简化的测试用例:
import * as React from 'react';
class Modal extends React.Component<{}> {
close = () => {};
}
declare const modal: Modal;
modal.close();
const modalRef = React.createRef<Modal>();
// Let's try giving this ref to the correct component…
// No error as expected :-)
<Modal ref={modalRef} />;
class SomeOtherComponent extends React.Component<{}> {}
// Let's try giving this ref to the wrong component…
// Expected type error but got none! :-(
<SomeOtherComponent ref={modalRef} />;
// Now when we try to use this ref, TypeScript tells us it's safe to do so.
// But it's not, because the ref has been incorrectly assigned to another component!
if (modalRef.current !== null) {
modalRef.current.close() // runtime error!
}
【问题讨论】:
-
您可以将
modalRef输入为Modal吗?const modalRef:Modal = ... -
不,因为 refs 是一种独特的类型。 (他们有一个名为
current的属性。) -
React.RefObject<Modal>怎么样? -
这不会改变任何东西,因为这与我的示例中
createRef返回的类型相同。 -
TypeScrip 不捕获所有错误。因为您也可以将字符串分配给错误的函数。它在语法上是正确的。但在语义上不正确。我只是在类似的情况下使用
React.createRef<ReactInstance>()。这样,两个组件都只是一个反应实例。
标签: reactjs typescript ref