在高阶组件中使用 ref

Har*_*rma 5 javascript reactjs

我有一个Tableref附加到的组件。

使用:Table.js

class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rows: 1,
      dataLength: props.dataLength,
    }
    this.tableRef = React.createRef(); 
  }

  componentDidUpdate() {
    //using ref
    this.tableRef.current ..... //logic using ref
    this.state.rows ..... //some logic
  }

  render() {
    <TableContainer ref={this.tableRef} />
    <CustomPagination />
  }
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但现在我的要求发生了变化,我想重用 Table 组件,并将分页应用于我的应用程序中的所有表。我决定做一个 HOC withCustomPagination

使用:withCustomPagination.js HOC

import CustomPagination from 'path/to/file';

const withCustomPagination = tableRef => Component => {
  return class WithCustomPagination extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        rows: 1,
        dataLength: props.dataLength,
      }
    }

    componentDidUpdate() {
      tableRef.current.state ..... //logic using ref, Error for this line
      this.state.rows ..... //some logic
    }

    render() {
      return (
        <Component {...state} />
        <CustomPagination />
      )
    }
  }
}

export default withCustomPagination;
Run Code Online (Sandbox Code Playgroud)

新的Table.js

import withCustomPagination from '/path/to/file';

const ref = React.createRef();

const Table = props => (
  <TableContainer ref={ref} />
);

const WrappedTable = withCustomPagination(ref)(Table);
Run Code Online (Sandbox Code Playgroud)

HOCwithCustomPagination返回一个类WithCustomPagination,该类具有componentDidUpdate在逻辑中使用 Table ref的生命周期方法。所以,我试图通过ref在创建Table.js作为参数withCustomPagination,即咖喱有refTable无状态组件。

这种使用ref是错误的,我得到错误:TypeError: Cannot read property 'state' of null

我尝试使用Forwarding Refs,但无法实现它。

我如何将表格传递refwithCustomPagination并能够在 HOC 中使用它?

zam*_*ber 1

要么重构你的代码,不使用 HOC,要么尝试使用React.forwardRef

\n\n
\n

引用 Aren\xe2\x80\x99t 已通过

\n\n

虽然高阶组件的约定是将所有 props 传递给包装组件,但这对于 refs 不起作用。\n 那 \xe2\x80\x99s 因为 ref 并不是真正的 prop \xe2\x80\x94与 key 一样,它\xe2\x80\x99 是由 React 专门处理的。如果将 ref 添加到其组件是 HOC 结果的元素,则该 ref 引用最外层容器组件的实例,而不是包装的组件。

\n\n

此问题的解决方案是使用 React.forwardRef API\n(随 React 16.3 引入)。在转发参考部分了解更多信息。

\n
\n\n

通过高阶组件:Refs Aren\xe2\x80\x99t 已传递

\n\n

转发引用部分中,有一些代码示例,您可以使用它来传递引用但在您的情况下尝试将它们拉起将失败:

\n\n
\n

警告:无状态函数组件不能被给予引用。尝试访问此引用将失败。

\n
\n\n

在一个项目中我们采取了不同的方法。有一个EnhancedTable组件可以处理所有分页逻辑,并且其本身具有哑表组件和分页组件。它工作得很好,但这意味着你必须钻取 props(或使用像 Redux 或 Mobx 这样的存储库)并添加新的来处理分页选项。这将导致一些重构Table用途的重构,你必须更加明确,但我将其视为一种福音而不是一种障碍。

\n