如何在样式组件中动态呈现内容之前的伪造
How to render pseudo before content dynamically in styled-component
我在 styled-components 中动态呈现伪内容之前遇到了问题。
我是不是做错了什么?
当我在内容之前静态渲染伪时没有问题,但当我动态尝试时它不起作用。
React 组件
const Test = (props) => {
return (
<Text before={12345}>
{props.children}
</Text>
);
};
带样式的组件(无效)
const Text = styled.span`
&:before {
content: ${props => {
console.log(props.before); // I see '12345' in log.
return props.before;
}
}
`;
样式化组件(效果很好)
const Text = styled.span`
&:before {
content: '12345'
}
`;
styled-components 的工作原理与 sass 相同,没有什么不同
const Text = styled.span`
&:before {
content: ${props => !!props.before ? props.before : " "};
}
`;
我是一个 // 渲染:"I am a "
引用自
那是因为 content
值必须在 css
的引号内
示例:
const Block = styled.div`
&:before {
display: absolute;
top:0;
content: '${props => props.before}'
}
`
请注意,我正在利用 ES6 new features,其中单个语句函数不需要使用大括号 {}
和 return
。
我所做的是为此使用 css 辅助函数:
const Text = styled.span`
&:before {
${props => !!props.before ?
css`content: props.before;` : css`content: ' '';`
};
}
`
我在 styled-components 中动态呈现伪内容之前遇到了问题。
我是不是做错了什么?
当我在内容之前静态渲染伪时没有问题,但当我动态尝试时它不起作用。
React 组件
const Test = (props) => {
return (
<Text before={12345}>
{props.children}
</Text>
);
};
带样式的组件(无效)
const Text = styled.span`
&:before {
content: ${props => {
console.log(props.before); // I see '12345' in log.
return props.before;
}
}
`;
样式化组件(效果很好)
const Text = styled.span`
&:before {
content: '12345'
}
`;
styled-components 的工作原理与 sass 相同,没有什么不同
const Text = styled.span`
&:before {
content: ${props => !!props.before ? props.before : " "};
}
`;
我是一个 // 渲染:"I am a "
引用自
那是因为 content
值必须在 css
示例:
const Block = styled.div`
&:before {
display: absolute;
top:0;
content: '${props => props.before}'
}
`
请注意,我正在利用 ES6 new features,其中单个语句函数不需要使用大括号 {}
和 return
。
我所做的是为此使用 css 辅助函数:
const Text = styled.span`
&:before {
${props => !!props.before ?
css`content: props.before;` : css`content: ' '';`
};
}
`