美文网首页
react displayName

react displayName

作者: 别过经年 | 来源:发表于2023-11-20 22:51 被阅读0次

通过react dev tools可以很方便的审查react组件元素,但是有时候会因为审查元素无法显示正确的组件名而烦恼。比如

1. 被forwardRef 或 memo 包裹的组件名称的显示问题

import { forwardRef, memo } from "react";

const NextList = memo(() => {
  return (
    <div>
      <b>list</b>
    </div>
  );
});

const Home = () => {
  return (
    <div>
      <h2>home</h2>
      <NextList></NextList>
    </div>
  );
};
被memo包裹的组件名

并没有显示为NextList,应该怎么解决?

  • 将被包裹的组件命名为List箭头函数
const List = () => {
  return (
    <div>
      <b>list</b>
    </div>
  );
};

const NextList = memo(List);
  • 将被包裹的组件命名为List普通函数
const NextList = memo(function List() {
  return (
    <div>
      <b>list</b>
    </div>
  );
});
function函数

react dev tools显示的名称为被包裹组件的名称List,而不是NextList。

  • 给包裹后的组件赋值displayName属性
const NextList = memo(function () {
  return (
    <div>
      <b>list</b>
    </div>
  );
});

NextList.displayName = "List";
赋值displayName属性

小结:个人觉得第二种办法比较方便,看个人习惯吧。

2. 没法区分不同的context

context.js

import { createContext } from "react";

export const ThemeContext = createContext(null);
export const SizeContext = createContext(null);

home.jsx

const Home = () => {
  return (
    <div>
      <h2>home</h2>
      <NextList></NextList>
      <ThemeContext.Provider value={"dark"}>
        <SizeContext.Provider value={"large"}>
          <Product></Product>
        </SizeContext.Provider>
      </ThemeContext.Provider>
    </div>
  );
};
react dev tools context

react dev tools并没有显示我们代码里的ThemeContext.Provider SizeContext.Provider,解决办法displayName

import { createContext } from "react";

export const ThemeContext = createContext(null);
ThemeContext.displayName = "Theme";

export const SizeContext = createContext(null);

SizeContext.displayName = "Size";
context displayname

在react-router@6的代码中也是这么处理的

export const LocationContext = React.createContext<LocationContextObject>(
  null!
);

if (__DEV__) {
  LocationContext.displayName = "Location";
}
react-router displayName

Avoid Anonymous Components With the displayName Property

相关文章

网友评论

      本文标题:react displayName

      本文链接:https://www.haomeiwen.com/subject/ijpvwdtx.html