23

我在 React 项目中使用样式化组件。当组件在浏览器中呈现时,它们被分配一个随机生成的类名,例如:

<div class="sc-KSdffgy oPwefl">

这个类名不能帮助我识别来自哪个组件<div>,那么有没有办法轻松做到这一点?

Ps 目前我正在将 attrs 添加到我的样式化组件中,以便我可以在开发工具中识别它们,例如:

const Foo = styled.div.attrs({
   'data-id': 'foo'
})`
    ...
`;
4

5 回答 5

36

这正是我们创建Babel 插件的原因,使用它时,您将获得包含您为组件提供的名称的类名称:

<div class="Sidebar__Button-KSdffgy oPwefl">

除此之外,我们还设置了displayName生成组件的名称,这意味着在您的 React DevTools 中,您将看到实际的组件名称,而不仅仅是 <div> 或 <Styled(Component)>。

要使用 Babel 插件,请安装它,npm install --save-dev babel-plugin-styled-components然后将其添加到您的 Babel 配置中:(例如,在您的.babelrc

plugins: ["styled-components"]

而已!快乐调试


请注意,如果您正在使用create-react-app,则无法更改 Babel 配置。我使用并建议react-app-rewired能够更改配置而无需弹出。我们还react-app-rewire-styled-components为您构建了自动集成 styled-components Babel 插件!

于 2017-08-04T11:21:08.620 回答
15

对于使用 create-react-app 的任何人,只需替换

import styled from "styled-components";

import styled from "styled-components/macro";

这将使您的样式组件类在其中包含其组件的名称。并且您只需查看它们的类名就可以知道哪些类引用了哪些组件;)

于 2020-09-02T18:15:48.707 回答
6

对于任何使用 的人create-react-app,另一种选择是使用样式化组件 babel 宏

  1. npm install --save babel-plugin-macros
  2. 在您的组件内部使用import styled from 'styled-components/macro';而不是import styled from 'styled-components';

您现在应该在开发工具中看到组件名称:

在此处输入图像描述

于 2020-03-27T14:19:02.713 回答
4

我正在考虑做同样的事情,并偶然发现了以下作为 attrs 的替代方法:

const Section = styled.div`
  background-color: #06183d;
  color: white;
  padding: 16px;
  margin-top: 16px;
  ${breakpoint("md")`
    border-radius: 5px;
  `}
`

Section.defaultProps = {
  "data-id": "Section"
}

使用 React.Component 的defaultProps. 它保持对styled.div清洁器的调用,并且在需要时应该更容易删除。

结果是: 在此处输入图像描述

于 2019-04-04T12:40:49.910 回答
0

如果您使用ts-loaderawesome-typescript-loadertypescript-plugin-styled-components

于 2020-06-20T12:34:33.847 回答