我在 React 项目中使用样式化组件。当组件在浏览器中呈现时,它们被分配一个随机生成的类名,例如:
<div class="sc-KSdffgy oPwefl">
这个类名不能帮助我识别来自哪个组件<div>
,那么有没有办法轻松做到这一点?
Ps 目前我正在将 attrs 添加到我的样式化组件中,以便我可以在开发工具中识别它们,例如:
const Foo = styled.div.attrs({
'data-id': 'foo'
})`
...
`;
我在 React 项目中使用样式化组件。当组件在浏览器中呈现时,它们被分配一个随机生成的类名,例如:
<div class="sc-KSdffgy oPwefl">
这个类名不能帮助我识别来自哪个组件<div>
,那么有没有办法轻松做到这一点?
Ps 目前我正在将 attrs 添加到我的样式化组件中,以便我可以在开发工具中识别它们,例如:
const Foo = styled.div.attrs({
'data-id': 'foo'
})`
...
`;
这正是我们创建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 插件!
对于使用 create-react-app 的任何人,只需替换
import styled from "styled-components";
至
import styled from "styled-components/macro";
这将使您的样式组件类在其中包含其组件的名称。并且您只需查看它们的类名就可以知道哪些类引用了哪些组件;)
对于任何使用 的人create-react-app
,另一种选择是使用样式化组件 babel 宏
npm install --save babel-plugin-macros
import styled from 'styled-components/macro';
而不是import styled from 'styled-components';
您现在应该在开发工具中看到组件名称:
我正在考虑做同样的事情,并偶然发现了以下作为 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
清洁器的调用,并且在需要时应该更容易删除。
如果您使用ts-loader
或awesome-typescript-loader
有typescript-plugin-styled-components。