假设我想创建一个名为 <NoPrint />
的样式组件将以下 CSS 添加到作为子元素传递的任何元素中:
@media print
{
display: none !important;
}
我怎样才能做到这一点?
我希望能够编写这样的样式组件:
<NoPrint><p>Some paragraph</p></NoPrint>
<NoPrint><Some>Some React component</Some></NoPrint>
我知道我可以写:
const NoPrint = styled.div`
@media print
{
display: none !important;
}
`
render(
<NoPrint>
<Something />
</NoPrint>
)
但是这个组件创建了一个包装 div,这是我不想要的。
最佳答案
这是因为你必须传入你想要样式的组件,IE:
不带包装器的组件样式
const NoPrint = styled(myComponent)`
@media print
{
display: none !important;
}
`
这将直接将自定义样式应用于元素而不使用包装器。
多态属性
另一种方法是使用“as”polymorphic prop
const Component = styled.div`
@media print
{
display: none !important;
}
`;
render(
<Component
as="button"
onClick={() => alert('It works!')}
>
Hello World!
</Component>
)
关于reactjs - 使用样式组件向子元素添加样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55922714/