问题
Am using styled components in React. Whenever i write the styles in styled component and if loads the application in the browser am getting some random classes name in the elements tab of developer tools. I just want to know whats happening behind the scene?
const Button = styled.a`
display: inline-block;
border-radius: 3px;
padding: 0.5rem 0;
margin: 0.5rem 1rem;
width: 11rem;
background: transparent;
color: white;
border: 2px solid white;
`
render(
<div>
<Button
href="https://github.com/styled-components/styled-components"
target="_blank"
rel="noopener"
primary
>
GitHub
</Button>
<Button as={Link} href="/docs">
Documentation
</Button>
)
if we inspect and check the element in the developer tools , i can able to see some random classes display like as follow;
<a
href="https://github.com/styled-components/styled-components"
target="_blank"
rel="noopener"
class = "sc-jDwBTQ "
>
GitHub
</a>
回答1:
This was about all I could find in the styled-components FAQ
Each node actually has two classes connected to it: one is static per component, meaning each element of a styled component has this class. It hasn't any style attached to it. Instead, it's used to quickly identify which styled component a DOM objects belongs to or to make minor changes in the DevTools. It's also used for component selectors. The static class probably will look something like:
.sc-fVOeaW
.The other is dynamic, meaning it will be different for every element of your styled component with different props, based on what the interpolations result in. It will probably look like
.fVOeaW
(note the lack of "sc" prefix.)For example, the styled component
<Button />
would render with the same static class every time. If the styles are changed using interpolations, like<Button secondary />
, then the dynamic class will be a different one, while the static class would remain the same.
Also, Motivation
No class name bugs: styled-components generates unique class names for your styles. You never have to worry about duplication, overlap or misspellings.
TL;DR They are automagically generated and maintained by styled-components
.
回答2:
Currently styled-components uses MurmurHash algorithm to create a unique identifier and then converts the hash number to alphabetic name.
Each component instance with unique props has it’s own CSS class name which is generated by means of the MurmurHash algorithm, the componentId and the evaluatedStyles string:
const className = hash(componentId + evaluatedStyles);
Then this class name is stored in the component state as generatedClassName.
回答3:
Are you using Material UI for reactjs by any chance? If so,then just check in the package.json about the version details. If it's version has "rc" appended to it, then please update it to the previous/next stable version.
来源:https://stackoverflow.com/questions/59961697/random-classes-getting-displayed-when-we-use-styled-components