首页 > 解决方案 > 如何在打字稿中使用 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”。

有什么建议吗,谢谢

标签: reactjstypescript

解决方案


这是工作示例

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>
})

推荐阅读