【问题标题】:Exporting in React higher order components在 React 中导出高阶组件
【发布时间】:2020-02-20 07:11:43
【问题描述】:
function logProps(WrappedComponent) {
  class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);
    }

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

  return LogProps;
}


class FancyButton extends React.Component {
  focus() {
    // ...
  }

  // ...
}

// Rather than exporting FancyButton, we export LogProps.
// It will render a FancyButton though.
export default logProps(FancyButton);

我从 react 文档中获取了这些代码,但是我对在此期间实际发生的事情感到困惑

export default logProps(FancyButton);

我的想法是它可能调用了函数 logProps,在 React 中它被认为是一个高阶组件,在这种情况下它应该使用大写字母以避免歧义。 logProp函数定义了一个类组件LogProps,类组件LogProps渲染了一个参数组件FancyButton。然后从函数返回类组件 LogProps。

import FancyButton from './FancyButton';

const ref = React.createRef();

// The FancyButton component we imported is the LogProps HOC.
// Even though the rendered output will be the same,
// Our ref will point to LogProps instead of the inner FancyButton component!
// This means we can't call e.g. ref.current.focus()
<FancyButton
  label="Click Me"
  handleClick={handleClick}
  ref={ref}
/>;

从函数 logProps 中返回的组件(LogProps,FancyButton)然后被导入并在

处实例化
<FancyButton
  label="Click Me"
  handleClick={handleClick}
  ref={ref}
/>  

这是正确的吗?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这对吗?

    几乎。

    如文档中所述,Higher Order Components:

    是一个函数,它接受一个组件并返回一个新组件。

    • HOCs 的名字不能以大写字母开头。
    • 返回的组件无需命名。

    为了简化,HOC 函数基本上只是返回一个新的和增强的组件。就是这样。

    这也可以:

    // camel case
    function logProps(WrappedComponent) {
      // no name
      return class extends React.Component {
        render() {
          return <WrappedComponent {...this.props} {...this.someEnhancements} />;
        }
      }
    }
    

    【讨论】:

    • 啊,对了,React 类/函数组件和高阶组件是有区别的,谢谢
    • @YaGetMeh 很高兴为您提供帮助!
    猜你喜欢
    • 2018-01-24
    • 2016-12-12
    • 2021-04-08
    • 1970-01-01
    • 2019-04-01
    • 2018-02-06
    • 2019-12-15
    • 2019-09-25
    • 1970-01-01
    相关资源
    最近更新 更多