Add Classes to Styled Component

谁说胖子不能爱 提交于 2020-06-08 08:14:09

问题


I am trying to add class names to a React Component to make it easier for me to customize that component using Styled Components. Here is a simplified outline of the component:

const SignupForm = props => (
    <form>
      <Input className="input" />
      <Button className="button" />
    </form>
  )

And here is how I would like to use it:

import { SignupForm } from '../path/to/signup-form'

  <Form />
...

const Form = styled(SignupForm)`
  .input {
     /* Custom Styles */
  }

  .button {
     /* Custom Styles */
  }
`

However, this does not work. Only if I create a wrapper Component will it work - like this:

import { SignupForm } from '../path/to/signup-form'

  <FormWrapper>
    <SignupForm/>
  <FormWrapper>
...

const FormWrapper = styled.div`
  .input {
     /* Custom Styles */
  }

  .button {
     /* Custom Styles */
  }
`

I'm wondering whether or not there is a way to access the .input and .button classes without having to create a wrapper class, i.e. via the actual imported class itself? If so, how?


回答1:


You need to provide className for the wrapper/container as styled-component injecting the styles through it:

const SignupForm = ({ className }) => (
  <form className={className}>
    <input className="input" />
    <button className="button">Button</button>
  </form>
);

const Form = styled(SignupForm)`
  .input {
    background-color: palegreen;
  }

  .button {
    background-color: palevioletred;
  }
`;



来源:https://stackoverflow.com/questions/59756648/add-classes-to-styled-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!