将类添加到样式化的组件 [英] Add Classes to Styled Component
问题描述
我正在尝试将类名添加到React组件,以使我更容易使用样式化组件自定义该组件.这是该组件的简化轮廓:
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 */
}
`
我想知道是否有一种方法可以访问 .input
和 .button
类而无需,而不必创建包装器类,即通过实际导入的类本身?如果可以,怎么办?
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?
推荐答案
您需要为包装器/容器提供 className
,作为 styled-component
注入样式:
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;
}
`;
这篇关于将类添加到样式化的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!