[英]React - Styled Component with multiple classes
I'm about to build a small project in react using styled component, however, I have a question for using this package. I would like to create a styled component that brings together several classes but I don't know how to do, for example:我正准备使用样式化组件构建一个反应小项目,但是,我对使用此 package 有疑问。我想创建一个样式化组件,将多个类组合在一起,但我不知道该怎么做,因为例子:
<div class="search-input search-input-small">
How to turn it into a styled component?如何把它变成一个有样式的组件? In css there are two different classes, but in styled component i don't know.在 css 中有两个不同的类,但在样式组件中我不知道。
Thank you.谢谢你。
There are a few ways to do this.有几种方法可以做到这一点。 For example, you could run with the base styling on a styled component and then "upgrade that with the additional styling.例如,您可以在带样式的组件上使用基本样式运行,然后“使用附加样式对其进行升级。
const Div = styled.div`
/// styles for className -> search-input
}`
const SmallDiv = styled(Div)`
/// styles for className -> search-input-small
`
Also, if you know SASS you can structure your CSS with nesting using &.此外,如果您知道 SASS,则可以使用 & 嵌套构建 CSS。 eg例如
const Div = styled.div`
.search-input {
//CSS
&-small {
//CSS
}
}
`
With styled-components, you can go with a similar format.使用 styled-components,您可以使用类似的格式 go。
Here we are creating a styled component named Div
, within the styled component I've declared classes .search-input
and .search-input.search-input-small
to style the div from your example.在这里,我们正在创建一个名为Div
的样式化组件,在样式化组件中我声明了类 .search- .search-input
和.search-input.search-input-small
以设置示例中 div 的样式。
The Div
is being treated as a parent container. Div
被视为父容器。
const Div = styled.div`
display: flex;
background-color: black;
.search-input {
background-color: blue;
}
.search-input.search-input-small {
color: white;
}
`;
We call the newly created styled component like this:我们这样调用新创建的样式组件:
export default function App() {
return (
<Div>
<div className="search-input search-input-small">Hello</div>
</Div>
);
}
As you can see the <div class="search-input search-input-small">
from your example is a child to the parent Div
.如您所见,示例中的<div class="search-input search-input-small">
是父级Div
的子级。 The parent Div does not require styles but I have included them for this example.父 Div 不需要 styles 但我已将它们包含在本例中。
Also here is a codesandbox with a working example.这里还有一个带有工作示例的codesandbox 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.