这是我的代码:
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仅是“ HTMLTableElement”。
有什么建议吗,谢谢?
答案 0 :(得分:0)
这是工作示例
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
如果还定义了ref.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>
})