我在React项目中使用样式组件。在浏览器中呈现组件时,会为它们分配一个随机生成的类名,例如:
<div class="sc-KSdffgy oPwefl">
这个类名不能帮助我识别<div>
来自哪个组件,所以有没有办法轻松完成这个?
P.S。目前我正在为我的样式组件添加attrs,以便我可以在开发工具中识别它们,例如:
const Foo = styled.div.attrs({
'data-id': 'foo'
})`
...
`;
答案 0 :(得分:15)
这正是我们创建Babel plugin的原因,在使用它时,您将获得包含您为组件命名的类名:
<div class="Sidebar__Button-KSdffgy oPwefl">
除此之外,我们还设置了生成组件的displayName
,这意味着在您的React DevTools中,您将看到实际的组件名称,而不仅仅是&lt; div&gt;或&lt; Styled(Component)&gt;。
要使用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
,它会自动为您设置样式组件Babel插件!
答案 1 :(得分:4)
对于使用create-react-app
的任何人,另一种选择是使用styled components babel macro
npm install --save babel-plugin-macros
import styled from 'styled-components/macro';
代替import styled from 'styled-components';
您现在应该在开发工具中看到组件名称:
答案 2 :(得分:4)
对于使用create-react-app的任何人,只需替换
import styled from "styled-components";
到
import styled from "styled-components/macro";
这将使您的样式化组件类在其中具有其组件的名称。您只需查看它们的类名就可以知道哪些类引用了哪些组件;)
答案 3 :(得分:0)
我一直在做同样的事情,偶然发现以下内容可以替代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
的呼叫更干净,并且在需要时应该更容易删除。
答案 4 :(得分:0)
如果您使用ts-loader
或awesome-typescript-loader
,则会有typescript-plugin-styled-components。