简体   繁体   English

如何将 displayName 设置为带有备忘录的 React 无状态组件?

[英]How set displayName to a React stateless component with memo?

This is a exemple the implementation of the stateless component:这是一个无状态组件的实现示例:

import React, { memo } from 'react';

const Create = memo(props => {
    return <div id={props.id}>CREATE TEST</div>;
});

Create.displayName = "Create";

export default Create;

In React Developer Tools on Chrome is displayed like a Anonymous component (highlighted line):在 Chrome 上的 React Developer Tools 中显示为匿名组件(突出显示的行):

在此处输入图像描述

You can use Object.assign :您可以使用Object.assign

const Create = memo(
  Object.assign(props => {
    return <div id={props.id}>CREATE TEST</div>;
  }, { displayName: 'Create' } )
)

You can also look at this issue , you may use any workaround solutions if above solution isn't helpful for you.您也可以查看此问题,如果上述解决方案对您没有帮助,您可以使用任何解决方法。

As for every component in React, React DevTools look for either the name or displayName property of the component itself.对于 React 中的每个组件,React DevTools 会查找组件本身的namedisplayName属性。

You can, therefore, simply set the displayName property:因此,您可以简单地设置displayName属性:

export const SomeButton = memo(() => { ... });
SomeButton.displayName = 'SomeButton';

But memo() itself retrieves the name from the passed component, so you can also use a named function expression instead of an arrow function:但是memo()本身从传递的组件中检索名称,因此您也可以使用命名 function 表达式而不是箭头 function:

export const SomeButton = memo(function SomeButton() { ... });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM