高阶组件·续1
务必复制静态方法
有时在 React 组件上定义静态方法很有用。例如,Relay 容器暴露了一个静态方法 getFragment 以方便组合 GraphQL 片段。
但是,当你将 HOC 应用于组件时,原始组件将使用容器组件进行包装。这意味着新组件没有原始组件的任何静态方法。
// 定义静态函数WrappedComponent.staticMethod = function() {/*...*/}// 现在使用 HOCconst EnhancedComponent = enhance(WrappedComponent);// 增强组件没有 staticMethodtypeof EnhancedComponent.staticMethod === 'undefined' // true
为了解决这个问题,你可以在返回之前把这些方法拷贝到容器组件上:
function enhance(WrappedComponent) { class Enhance extends React.Component {/*...*/} // 必须准确知道应该拷贝哪些方法 :( Enhance.staticMethod = WrappedComponent.staticMethod; return Enhance;}
但要这样做,你需要知道哪些方法应该被拷贝。你可以使用 hoist-non-react-statics 自动拷贝所有非 React 静态方法:
import hoistNonReactStatic from 'hoist-non-react-statics';function enhance(WrappedComponent) { class Enhance extends React.Component {/*...*/} hoistNonReactStatic(Enhance, WrappedComponent); return Enhance;}
除了导出组件,另一个可行的方案是再额外导出这个静态方法。
// 使用这种方式代替...MyComponent.someFunction = someFunction;export default MyComponent;// ...单独导出该方法...export { someFunction };// ...并在要使用的组件中,import 它们import MyComponent, { someFunction } from './MyComponent.js';
Refs 不会被传递
虽然高阶组件的约定是将所有 props 传递给被包装组件,但这对于 refs 并不适用。那是因为 ref 实际上并不是一个 prop - 就像 key 一样,它是由 React 专门处理的。如果将 ref 添加到 HOC 的返回组件中,则 ref 引用指向容器组件,而不是被包装组件。
这个问题的解决方案是通过使用 React.forwardRef API(React 16.3 中引入)。前往 ref 转发章节了解更多。
