React style -components::before和::after伪元素在传递函数时不显示



我想将::before::after伪元素添加到有样式组件的css样式对象中,这样我就可以在多个其他样式元素中重用它们(我在示例代码中为AboutWrapper这样做)。但是,当我运行代码时,::after没有出现。::before正在显示。当我改变它们在代码中的位置时,情况正好相反。我注意到,当我注释出设置top,leftbottom的函数并用常量替换它们时,两个伪元素都出现了。有什么问题吗?

不幸的是,代码片段在这里的Stackoverflow是不可运行的,我不知道为什么…也许我需要以某种方式包含有样式的组件?

import React from 'react'
import styled, { css } from 'styled-components'

export const showHtmlTagStyle = css`
position: relative;     // important for the before and after
&::before {
content: '<section>';
font-family: 'La Belle Aurore', cursive;
color: #fff; 
font-size: 18px;
position: absolute;
top: ${(props) => (props.tagTop ? props.tagTop : '1rem') };//1rem;
left: ${(props) => (props.tagLeft ? props.tagLeft : '2rem')};//2rem;
}
&::after {
content: '/section';
font-family: 'La Belle Aurore', cursive;
color: #fff; 
font-size: 18px;
position: absolute;
bottom: ${(props) => (props.tagBottom ? props.tagBottom : '1rem') };//1rem;
left: ${(props) => (props.tagLeft ? props.tagLeft : '2rem')};//2rem;
}
`
export const AboutWrapper = styled.div`
max-width: 1000px;
height: 100%;
display: flex;
justify-content: center;
${showHtmlTagStyle}
`
const AboutSection = () => {
return (
<AboutWrapper tagTop='1rem' tagLeft='2rem'>
Just some random Text that should have a 'before' tag before it and an 'after' tag after it.
</AboutWrapper>
)
}

ReactDOM.createRoot(
document.getElementById("root")
).render(
<AboutSection />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

您可以尝试使用1:而不是2 (::),如此答案中所述

export const showHtmlTagStyle = css`
position: relative;     // important for the before and after
&:before {
content: '<section>';
font-family: 'La Belle Aurore', cursive;
color: #fff; 
font-size: 18px;
position: absolute;
top: ${(props) => (props.tagTop ? props.tagTop : '1rem') };//1rem;
left: ${(props) => (props.tagLeft ? props.tagLeft : '2rem')};//2rem;
}
&:after {
content: '/section';
font-family: 'La Belle Aurore', cursive;
color: #fff; 
font-size: 18px;
position: absolute;
bottom: ${(props) => (props.tagBottom ? props.tagBottom : '1rem') };//1rem;
left: ${(props) => (props.tagLeft ? props.tagLeft : '2rem')};//2rem;
}
`

最新更新