【问题标题】:React Components - No Inheritance, how can pass ref or use HOC for my BaseComponentReact Components - 没有继承,如何为我的 BaseComponent 传递 ref 或使用 HOC
【发布时间】:2020-01-03 02:02:11
【问题描述】:

我正在构建一个 Web 组件库,其中包含一系列理想地继承/利用 BaseComponent 的组件。经过一番阅读,在 React 中不推荐继承,而是我可以使用 forwardRef?或者可能是高阶组件?唯一的一点,我对这个概念不是很熟悉,也找不到适合我的案例的好例子。希望有人能告诉我如何解决这个问题,最佳实践是什么?

我想到的 BaseComponent 技术之一是利用 IntersectionObserver 来触发动画。你可以想象,我不想把这个逻辑放在多个地方。对于有一个基本示例的厌倦,下面我只是在 BaseComponent 上有一个单击事件侦听器:

class Image extends React.Component {
  render() {
    return (     
      <div>
        <div>
          <img className={className} src={src} alt={alt} />     
        </div>   
      </div> 
    );
  }
}

export default Image;
// export default withMagic(Image); ??


class BaseComponent extends React.Component {

  withMagic() {

  }

  componentDidMount() {
    {/* ref should be <img> DOM element */}
    ref.addEventListener("click", this.handleClick);
  }
}

export BaseComponent();


谢谢

【问题讨论】:

    标签: reactjs components ref ad-hoc-distribution


    【解决方案1】:

    HoC 可能是更好的解决方案

    // 2. WrappedComponent
    export default WrappedComponent => {
        // If u want to deal with class
        class NewComponent extends React.Component {
             //3
             handleClick = () => {
                  // Your Events
             }
             render () {
                 //4
                 return <WrappedComponent {...this.props} handleClick={this.handleClick} />
             }
        }
        // If u want to deal with functional Component
        const NewComponent = props => {
            const handleClick = () => // your events
            return <WrappedComponent {...props} handleClick={handleClick} />
        }
    
        return NewComponent
    }
    

    如何使用?

    import withClick from 'path/withClick'
    const A = props => {
        return (
             //4
             <button onClick={props.handleClick}>Click here</button>
        )
    }
    
    // 1. 
    export default withClick(A)
    

    这个魔法是如何工作的?

    1. 你正在使用 withClick 方法,将 A 组件作为参数传递
    2. A 组件在withClick 函数内命名为WrappedComponent
    3. 在 withClick 函数中,你用你想要的处理程序、逻辑甚至状态创建一个新组件,然后将它们作为道具传递给WrappedComponent
    4. 之后,您当前的组件将具有这些处理程序或逻辑

    如果你想传递参数,你可以使用返回高阶组件的高阶函数,比如

    export default (params1, params2, ...paramsn) => WrappedComponent => {
    // remain like the same
    }
    

    【讨论】:

    • 感谢 Kaslie,这绝对有帮助!我需要但缺少的一件事是参考,但以下工作:return &lt;WrappedComponent ref={(ref) =&gt; this.ref = ref} {...props} handleClick={handleClick} /&gt;
    • 很好......,我可以知道你为什么需要参考吗?如果您想访问孩子的道具、状态或功能,您不必使用 ref 吗?
    猜你喜欢
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 2020-01-18
    • 2018-06-05
    • 2016-12-07
    • 2017-08-19
    • 2013-06-13
    • 2020-08-11
    相关资源
    最近更新 更多