有啥方法可以创建一个使用 WrappedComponent 中的方法的 HOC?

Posted

技术标签:

【中文标题】有啥方法可以创建一个使用 WrappedComponent 中的方法的 HOC?【英文标题】:Is there any way to create a HOC that uses methods from the WrappedComponent?有什么方法可以创建一个使用 WrappedComponent 中的方法的 HOC? 【发布时间】:2022-01-15 13:51:15 【问题描述】:

我想创建一个看起来或多或少像这样的自动刷新 HOC:

export function withAutoRefresh(WrappedComponent) 
  return class extends React.Component<any, any> 
    constructor(p: Readonly<any>) 
      super(p);
    

    interval: NodeJS.Timeout;

    componentDidMount() 
        this.interval = setInterval(() => theFunctionToRefreshWhichIsFromTheWrappedComponent(), 5000)
    

    componentWillUnmount() 
        clearInterval(this.interval)
    

    render() 
      return (
        <WrappedComponent ...this.props />
      );
    
  ;

我现在的问题是,我想刷新的功能只能在WrappedComponent 中使用。有什么方法可以实现这一点或类似于我所描述的吗?

【问题讨论】:

【参考方案1】:

这其实很简单,我找到了方法。 我只需要用refreshFunction 属性向这个组件添加一个状态,并将一个setter 函数作为prop 传递给WrappedComponent。草稿看起来或多或少是这样的:

constructor(p: Readonly<any>) 
    super(p);
    this.state = 
        refreshFunction: () => void 0
    


...

setRefresh(newFunction) 
    this.setState(
        ...this.state,
        refreshFunction: newFunction
    )


render() 
  return (
    <WrappedComponent ...this.props setRefresh=this.setRefresh />
  );

【讨论】:

以上是关于有啥方法可以创建一个使用 WrappedComponent 中的方法的 HOC?的主要内容,如果未能解决你的问题,请参考以下文章