javascript - 如何使用更高阶的组件动态设置 displayName ?

标签 javascript reactjs ecmascript-6

我正在尝试动态设置 displayName,因为每个组件都呈现为 <Component ... />并使其无法调试。到目前为止我已经设置了static displayName在每个组件上都运行良好,只是有很多重复的代码。

许多组件扩展了该组件,因此导致完全由未命名组件组成的层次结构。我怎样才能保存设置static displayName在扩展 Component 的每个组件上?

根组件

export class Component extends React.Component {
  static component = 'span';
  static style = {
    base: {}
  };

  constructor() {
    super(...arguments);
    this.style = this.constructor.style;
    this.switches = this.constructor.switches;
    this.component = this.constructor.component;
    // this.displayName = this.constructor.displayName;
  }

  getRenderProps() {
    ...
    return props;
  }

  render() {
    return React.createElement(this.component, this.getRenderProps(), this.props.children);
  }
}

其他类

class SomeClass extends Component {
   ...
}

SomeClass 现在呈现为 <Component>除非明确设置 static displayName其结果是:

enter image description here

最佳答案

const decorate = <P extends object>(
    Component: React.ComponentType<P>,
    displayName?:string
  ): React.FC<P> => ({
      ...props
  }: P) =>{
      const WithName = withStyles({})(Component as React.FC) 
      WithName.displayName = displayName
    return <WithName {...props as P} />
  }

然后像这样使用:

(注意!需要在组件之外)

const MyComp = decorate(Compo, "MyComp")

如果有人找到了更简洁的方式,请标记我的名字

关于javascript - 如何使用更高阶的组件动态设置 displayName ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938095/

相关文章:

javascript - 如何将映射值返回到以逗号分隔的对象 [] 中

Javascript |针对对象循环遍历对象数组

javascript - 从文本区域内的文本中删除空格

php - 控制浏览器缓存

node.js - 如何在 React 中导出用于服务器端渲染的组件

javascript - React中如何获取某个状态下数组的长度?

javascript - Vue.js:如何访问 vm-router 创建的 vm 对象?

javascript - 递归地将javascript文件目录压缩为单个文件

javascript - 尝试使用isNaN方法清理输入,但它会使while循环崩溃

javascript - 为什么我的 img 中的 require() 在与 Bulma 一起使用时无法正常工作?