reactjs - 如何在打字稿中使用 useEffect 和 forwardRef?
问题描述
这是我的代码:
import React from 'react';
type shapeTable = {
data: string[][];
onMount?: (tableWidth: string) => void;
};
type Ref = HTMLTableElement;
const Table = React.forwardRef<Ref, shapeTable>(({ data, onMount }, ref) => {
React.useEffect(() => {
console.log('ref = ', ref);
if (ref) {
console.log('ref.current = ', ref.current);
}
// const $table = ref.current;
// if (ref && onMount) {
// const tableWidth:string = window.getComputedStyle($table).getPropertyValue("width");
// onMount(tableWidth);
// }
});
return data.length ? (
<table ref={ref}>
<tbody>
{data.slice(1).map(tr => (
<tr>
{tr.map(item => (
<td>{item}</td>
))}
</tr>
))}
</tbody>
</table>
) : null;
});
错误
它在 ref.current 上失败
它似乎与 ref.current 斗争。
我正在努力强制 Ref 只是“HTMLTableElement”。
有什么建议吗,谢谢
解决方案
这是工作示例
const { useState, useRef, createRef, forwardRef, useEffect } = React;
const Table = forwardRef((props, ref) => {
useEffect(() => {
console.log('ref: ', ref && ref.current);
}, [ref])
return <table ref={ref}>
{props.children}
</table>
})
const App = () => {
const ref = useRef();
return <Table ref={ref}>
<tbody></tbody>
</Table>
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>
- 编辑
当您在智能感知中查看已解析的 ref 类型时,这是一个非常可怕的定义
((instance: HTMLTableElement | null) => void) | React.MutableRefObject<HTMLTableElement | null> | null
这意味着您必须检查是否ref
已定义并且ref
不是function
而ifref.current
也被定义,只是为了&&
继续
...或者只是投给任何人,不要打扰。
由你决定
const Table = React.forwardRef<HTMLTableElement >((props, ref) => {
React.useEffect(() => {
if(ref && typeof ref !== "function" && ref.current) {
console.log('ref: ', ref.current);
// ref.current.getBoundingClientRect()
}
}, [ref])
return <table ref={ref}>
{props.children}
</table>
})
推荐阅读
- java - 服务器进入无限循环并给出 GOOGLE_APPLICATION_CREDENTIALS 异常
- python - 将预言家预测反馈到数据集 - Python
- visual-studio-extensions - VS 2019 扩展以在项目加载时运行资源生成器
- java - Android & Java:String.getBytes() 无法正确解析转义字符
- dremio - 如何在dremio中添加新的数据源
- php - 如何回显一个对象?
- php - 在 result_array() 中解码数据库结果中存储的 JSON 值
- c# - 在游戏对象中找到具有名称和组件的游戏对象?
- javascript - 相邻的 JSX 元素必须被包裹在一个封闭标签 React Native 中
- sass - “错误:找不到或无法读取要导入的文件:compass/css3