我正在使用样式组件,并且想要定位
Text
的第一个子组件,但我无法这样做。
const Text = styled.p`
font-size: 12px;
&:first-child {
margin-bottom: 20px;
}
`;
... component
return(
<div>
<p>I am just regular text</p>
<p>Me too</p>
<Text>Hello Joe</Text> // this should have the margin bottom
<Text>Goodbye</Text >
</div>
)
终于明白你的问题了。样式化组件与前两个原生
p
标签混淆(从我的角度来看),这就是不应用 CSS 的原因。
我将使用这样的解决方法:
const Text = styled.p`
font-size: 12px;
color: blue;
&:nth-child(3) {
margin-bottom: 20px;
color: red !important;
}
`;
通过执行此操作,您将为 CSS 选择第三个子级(包括前两个
p
标签)
或者,您可以执行以下操作:为标签添加类名称并为该类提供 CSS。
const Text = styled.p`
font-size: 12px;
color: blue;
&.colors {
margin-bottom: 20px;
color: red !important;
}
`;
<div>
<p>I am just regular text</p>
<p>Me too</p>
<Text className="colors">Hello Joe</Text>
<Text>Goodbye</Text>
</div>
这是演示
希望有帮助:)
这样使用
const Text = styled.p`
font-size: 12px;
> * {
&:first-child {
margin-bottom: 20px;
}
}
`;
&
和:first-child
之间不应有空格
&:first-child {
margin-bottom: 20px;
}
最好在某些样式组件上使用 :last-of-type 而不是使用 :nth-child 并且效果完美
export default styled.div`
:last-of-type {
background: red;
}`
const Text = styled.p`
font-size: 12px;
color: blue;
&:nth-child(3) {
margin-bottom: 20px;
color: red !important;
}
`;
正如我们在其他答案中看到的那样,这完全是可能的。问题是,使用第一个子级或第n个子级解决方案时,您往往会最终到达 DOM 层次结构,从而产生各种以后很难解决的特殊性问题。
样式化组件的美妙之处在于您通常将样式应用于元素本身,这意味着您的样式与组件保持紧密耦合。组件变得可移植,并且很容易找到可能在复杂应用程序中导致问题的 CSS 行。
例如,如果我要以不同的方式对 ul 中列表项中的第一个
<a>
进行样式设置,我需要将 :first-child
放在层次结构的更上层,从而破坏封装。
解决这个问题的简单方法是认识到样式化组件是一个可以接收参数的函数:
<StyledListItem index={index} />
然后在组件中接收该参数:
export const StyledListItem = styled.li<{index?: number}>`
${
({index}) => {
if (index === 3) return `
color: red;
border: 2px dotted pink;
`
if (index === 0) return `
border-left: none
`
}
}
`
JS 中的 CSS 促进了这些类型的编程解决方案,如果你利用它们,你的生活会更轻松。
尝试将样式与您想要设置样式的 HTML 标签一起使用, 在你的情况下,它将是:
p:first-child {
// your style here
}