【问题标题】:component definition is missing display name on HOC组件定义在 HOC 上缺少显示名称
【发布时间】:2019-02-09 16:09:59
【问题描述】:

我正在尝试创建一个更高阶的组件,但不断得到这个 eslint 警告。

组件定义缺少显示名称

我尝试添加如下所示的显示名称,但它仍然报错。

import React from 'react';

const HOC = props => (WC) => {
  WC.displayName = 'test'
  return (
    <WC />
  );
}

export default HOC;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你需要纠正两件事。

    首先:修复功能组件声明的顺序。

    第二:将displayName设置为HOC返回的组件

    const HOC = WC => {
      const MyComp = (props) => {
        return (
            <WC {...props} />
          );
      }
      MyComp.displayName = 'test'
      return MyComp;
    }
    

    进行上述更改后。你只需要像使用 HOC 一样

    const MyCompWithHoc = HOC(CompA);
    

    并像这样渲染它

    <MyCompWithHoc propsA={'A'} {...otherPropsYouWantToPass} />
    

    【讨论】:

    • 我收到一条错误消息Cannot add property displayName, object is not extensible
    【解决方案2】:

    HOC 是缺少 displayName 属性的组件。您上面的代码正在更改您不想要的 WC 的 displayName 属性。

    HOC.displayName = 'some higher component'

    【讨论】:

    • 我已经试过它仍然抱怨厕所是问题。
    【解决方案3】:

    您的 HOC 应该将组件作为第一个参数而不是 props,请参阅 React 文档中的示例:https://reactjs.org/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging

    编辑:您可以通过返回一个功能组件来传递它的道具:

    const HOC = WC => props => {
      WC.displayName = 'test'
      return (
        <WC {...props} />
      );
    }
    

    或者在设置displayName后直接返回包装好的组件:

    const HOC = WC => {
      WC.displayName = 'test';
      return WC;
    }
    

    【讨论】:

    • 那么我将如何传递它的道具。
    猜你喜欢
    • 2020-06-19
    • 1970-01-01
    • 2021-12-13
    • 2022-06-17
    • 2019-03-30
    • 1970-01-01
    • 2021-08-16
    • 2020-07-28
    相关资源
    最近更新 更多