第一个 HOC (Higher-Order Components)( Day21 )

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature. - React Document

higher-order component 是一个函式,输入一个 component 并回传一个 component。

我的第一个 HOC

const myFirstHoc = (Component, handler) => {
   return (props) =>
    <Component
      {...props}
      onClick={(event) => handler.click(event)}
    />
}

Codepen 完整程序

HOC 的几种形式

单一参数

const NavbarWithRouter = withRouter(Navbar);

两个参数,Component + 设定

const CommentWithRelay = Relay.createContainer(Comment, config);

HOC 回传 HOC

// React Redux's `connect`
const ConnectedComment = connect(commentSelector, commentActions)(CommentList);

//同等於
// connect is a function that returns another function
const enhance = connect(commentListSelector, commentListActions);
// The returned function is a HOC, which returns a component that is connected
// to the Redux store
const ConnectedComment = enhance(CommentList);

HOC 注意事项

不要在 render 方法中使用 HOC

render() {
  // A new version of EnhancedComponent is created on every render
  // EnhancedComponent1 !== EnhancedComponent2
  const EnhancedComponent = enhance(MyComponent);
  // That causes the entire subtree to unmount/remount each time!
  return <EnhancedComponent />;
}

将 React component 的静态方法复制过来

function enhance(WrappedComponent) {
  class Enhance extends React.Component {/*...*/}
  // Must know exactly which method(s) to copy :(
  Enhance.staticMethod = WrappedComponent.staticMethod;
  return Enhance;
}

HOC 会通过所有的 props, 但 Refs 不会

初步学习觉得 HOC 很抽象,而 HOC 有很多不同的形式跟工具,例如复制静态方法会用 hoist-non-react-statics 套件,第三方实作向 Redux 的 connect 和 Relay 的 createFragmentContainer 等,值得後续深入研究。

以上今天。

参考资料:
https://zh-hant.reactjs.org/docs/higher-order-components.html


<<:  #21 让 Automation 与 Chat Bot 连动

>>:  Day20:终於要进去新手村了-Javascript-函式-建立函式

#18 JS: Intro to function

What is function? Simple explanation: when you fin...

二元树之 IF 下策 - DAY 18

前言 昨天可以看到在知道数量的状况,去调动顺序,就可以减少 IF 触发数,接下来会建立霍夫曼树,达到...

[Golang]效能测试(Benchmark)简介-心智图总结

1. Benchmark,是GO语言用来做函数的效能测试。 2. Go语言对效能测试函数的名称与函数...

D17 - 从TiDB将资料同步出去

TiDB可以同步MySQL的资料异动,那麽能不能反过来让其他DB同步随着TiDB异动呢。 答案是可以...

[Day30] 谁怕谁,再来啊!

呼 ~ 终於到了最後一天了,这三十天,说真的有点痛苦煎熬 XD 不过我们先来回顾这次铁人赛介绍了哪些...