简体   繁体   中英

how to attach styled-component style to a component className props?

hi guys i've create a react component. in react way i could easily attach css style to my component via className="some_style"

but how do i attach my styled component to these className props.

say per as

<Component className="styled_component" />

i don't know which approach im gonna use ? Thanks

Well you can't because you don't know which classname will your css-in-js gets compiled to. Styled component helps you write the CSS of a particular component in JS. You can try writing the CSS of <Component /> in Component.js file. If the CSS class is reuseable, create a common CSS file and include it in index.js/App.js

When using styled-components, you don't have to use the className prop on your components anymore. Let's say you've got a div that you want to style. First declare the div as a styled-component.

const StyledDiv = styled.div`
   background-color: blue;
`

Notice how I'm using styled. div as it's a div element I'm using. Then to render this componenet, you do the same as you would with any other component.

return(
   <StyledDiv />
)

The div will then render with the css you applied to it, you don't have to interact with className .

This usually works well for me (even if hilariously I actually found this question cause I'm having trouble with a specific situation using className ):

const Component = styled.div.attrs({
  className: '[add your classes here]'
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM