reactjs - 如何在反应和打字稿中为 forwardRef 扩展引用类型以允许多个引用
问题描述
此代码在打字稿下验证:
type Ref = HTMLTableElement;
const Table = forwardRef<Ref, shapeTable>(({filtered, handleSort, paginationOptions, summary, onMount}, refTable) => {
useEffect(() => {
if(refTable && typeof refTable !== 'function' && refTable.current) {
const tableWidth:string = window.getComputedStyle(refTable.current).getPropertyValue("width");
onMount(tableWidth);
}
}, [refTable, onMount]);
此代码在打字稿下无效:
当我将类型 refTable 放入如下对象中并更新 Ref 类型以允许这样做时,它不会验证。我怎样才能解决这个问题?我需要能够将多个 ref 传递给 forwardRef。我以前没有使用打字稿就这样做了,它可以工作。所以关于 forwardRef 的一些东西似乎坚持只有一种 ref 类型可以通过。除非更新我的 Ref 类型更简单:
键入'((实例:Ref | null)=> void)| 可变引用对象 | null' 不可分配给类型 'Ref'。类型“null”不能分配给类型“Ref”。
type Ref = {
refTable: HTMLTableElement
};
const Table = forwardRef<Ref, shapeTable>(({filtered, handleSort, paginationOptions, summary, onMount}, ref) => {
const {refTable}:Ref = ref;
useEffect(() => {
if(refTable && typeof refTable !== 'function' && refTable.current) {
const tableWidth:string = window.getComputedStyle(refTable.current).getPropertyValue("width");
onMount(tableWidth);
}
}, [refTable, onMount]);
解决方案
您对哪些属性在哪些对象上感到困惑。在第二个示例中,您有一个具有refTable
属性的对象的引用。如果您的 ref 是一个 ref 对象(不是回调 ref),那么它看起来像:
ref = {
current: {
refTable: HTMLTableElement,
}
}
所以你需要先在current
ref 上寻找,然后在寻找on 。refTable
ref.current
修改后的代码:
const Table = forwardRef<Ref, shapeTable>(({ filtered, handleSort, paginationOptions, summary, onMount }, ref) => {
useEffect(() => {
if (ref && typeof ref !== 'function' && ref.current) {
const table = ref.current.refTable;
const tableWidth = window.getComputedStyle(table).getPropertyValue("width");
onMount(tableWidth);
}
}, [ref, onMount]);
...
请注意,不建议useEffect
在依赖项中使用 refs 。
推荐阅读
- javascript - 打字稿条件函数签名 - 基于选项中的布尔值
- c# - 配置 Seq 以自动发送电子邮件的示例
- angular - Angular - 如何从祖父组件访问子组件?
- apache-kafka - 如何从 Neo4j 4.3-enterprise 发布 Kafka 消息
- linux - uuid-dev 未安装,Ubuntu
- firebase - 颤振应用程序在运行时仅显示白屏
- node.js - 相同状态码的 TSOA 多重响应
- django - 在 django 中赋值之前引用的局部变量“params”
- z3 - 是否可以在 smtlib 中声明函数排序?
- javascript - 根据特定日期显示名称值