首页 > 解决方案 > 在高阶组件中使用 ref

问题描述

我有一个想要附加的Table组件。ref

使用: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 />
  }
}

这工作正常,但现在我的要求已经改变,我想重用 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;

新的Table.js

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

const ref = React.createRef();

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

const WrappedTable = withCustomPagination(ref)(Table);

HOCwithCustomPagination返回一个类,该类WithCustomPagination具有componentDidUpdate在逻辑中使用 Table ref 的生命周期方法。所以我尝试将refTable.js中创建的作为参数传递给withCustomPagination,即 curried withrefTablestateless 组件。

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

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

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

标签: javascriptreactjs

解决方案


在这种情况下,您可以使用useImperativeHandle

这意味着您必须转发ref并指定要ref在功能组件内共享的函数或对象,或者...。

这是我的临时示例:

import React from 'react';
import { View } from 'react-native';

export function CommonHoc(WrappedComponent) {

    const component = class extends React.Component {

         componentDidMount() {
           this.refs.myComponent.showAlert();

        }

        render() {
            return (
                <>
                    <WrappedComponent
                        ref='myComponent'
                        {...this.state}
                        {...this.props}
                    />
                </>
            );
        }
    };
    return component;
}

这是我的无状态组件

const HomeController=(props,ref)=> {

    useImperativeHandle(ref, () => ({

        showAlert() {
            alert("called");
        },
    }));

    return (
        <Text>home</Text>
    );
};
export default CommonHoc(forwardRef(HomeController));

推荐阅读