【问题标题】:Can I pass a className as a prop to StyledComponent in ReactJS?我可以将 className 作为道具传递给 ReactJS 中的 StyledComponent 吗?
【发布时间】:2020-09-14 05:40:12
【问题描述】:
我有一个简单的按钮组件,其中的动作作为道具传递。我决定使用 Styled-Components 对其进行样式设置。
在我的 React 应用程序中,我有三个具有不同操作的按钮,我希望它们具有不同的颜色。
我可以在 StyledComponent 中编写一些 CSS 类 并作为道具传递 和“指示符”应该为我的组件设置样式吗?
【问题讨论】:
标签:
javascript
css
reactjs
styled-components
【解决方案1】:
您可以像这样在 styled-components 中设置类的样式:
const Button = styled.button`
&.className {
// some styles
}
【解决方案2】:
当然,这是样式化组件最基本的功能之一。
一种方法是创建不同的组件:
const MyButton = styled.button`
font-size: 12px;
border: 1px solid red;
`;
const FooButton = styled(MyButton)`
color: red;
`;
const BooButton = styled(MyButton)`
color: blue;
`;
另一种方法是使用道具:
const MyButton = styled.button`
font-size: 12px;
border: 1px solid red;
color: ${({type}) => type === 'foo' ? 'red' : 'blue'};
`;
...
...
<MyButton type={'foo'} />
对于您最初的问题,您可以这样做。但在大多数情况下,以这种方式使用类名并不那么“样式化组件”。