Javascript React 中的 CSS 伪元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28269669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS pseudo elements in React
提问by Michael Johansen
I'm building Reactcomponents. I have added CSS inline in the components as suggested in this brilliant presentationby one of the guys behind React. I've been trying all night to find a way to add CSS pseudo classes inline, like on the slide titled "::after" in the presentation. Unfortunately, I do not just need to add the content:"";property, but also position:absolute; -webkit-filter: blur(10px) saturate(2);. The slides show how to add content through {/* … */}, but how would you add other properties?
我正在构建React组件。我在组件中添加了 CSS 内联,正如React 背后的一个人在这个精彩的演示中所建议的那样。我整夜都在尝试找到一种方法来内联添加 CSS 伪类,就像演示文稿中标题为“::after”的幻灯片一样。不幸的是,我不仅需要添加content:"";属性,还需要添加position:absolute; -webkit-filter: blur(10px) saturate(2);. 幻灯片显示了如何通过 来添加内容{/* … */},但您将如何添加其他属性?
回答by Michael Johansen
Got a reply from @Vjeux over at the Reactteam:
收到来自React团队的@Vjeux 的回复:
Normal HTML/CSS:
普通 HTML/CSS:
<div class="something"><span>Something</span></div>
<style>
.something::after {
content: '';
position: absolute;
-webkit-filter: blur(10px) saturate(2);
}
</style>
React with inline style:
与内联样式反应:
render: function() {
return (
<div>
<span>Something</span>
<div style={{position: 'absolute', WebkitFilter: 'blur(10px) saturate(2)'}} />
</div>
);
},
The trick is that instead of using ::afterin CSS in order to create a new element, you should instead create a new element via React. If you don't want to have to add this element everywhere, then make a component that does it for you.
诀窍是不要::after在 CSS 中使用来创建新元素,而是应该通过 React 创建一个新元素。如果您不想在任何地方都添加这个元素,那么制作一个为您做的组件。
For special attributes like -webkit-filter, the way to encode them is by removing dashes - and capitalizing the next letter. So it turns into WebkitFilter. Note that doing {'-webkit-filter': ...}should also work.
对于像 这样的特殊属性-webkit-filter,对它们进行编码的方法是删除破折号 - 并将下一个字母大写。所以变成了WebkitFilter. 请注意,这样做{'-webkit-filter': ...}也应该有效。
回答by Wiktor Kozlik
Inline styles cannot be used to target pseudo-classes or pseudo-elements. You need to use a stylesheet.
内联样式不能用于定位伪类或伪元素。您需要使用样式表。
If you want to generate CSS dynamically, then the easiest way is to create a DOM element <style>.
如果你想动态生成 CSS,那么最简单的方法就是创建一个 DOM 元素<style>。
<style dangerouslySetInnerHTML={{
__html: [
'.my-special-div:after {',
' content: "Hello";',
' position: absolute',
'}'
].join('\n')
}}>
</style>
<div className='my-special-div'></div>
回答by Joshua Robinson
Inline styling does not support pseudos or at-rules (e.g., @media). Recommendations range from reimplement CSS features in JavaScript for CSS states like :hovervia onMouseEnterand onMouseLeaveto using more elements to reproduce pseudo-elements like :afterand :beforeto just use an external stylesheet.
内联样式不支持伪或 at 规则(例如,@media)。建议的范围从重新实现CSS特征在JavaScript为CSS状态等:hover通过onMouseEnter并onMouseLeave用多种元素来再现伪元素像:after和:before只是使用一个外部的样式表。
Personally dislike all of those solutions. Reimplementing CSS features via JavaScript does not scale well -- neither does adding superfluous markup.
个人不喜欢所有这些解决方案。通过 JavaScript 重新实现 CSS 功能不能很好地扩展——添加多余的标记也不能。
Imagine a large team wherein each developer is recreating CSS features like :hover. Each developer willdo it differently, as teams grow in size, if it can be done, it will be done. Fact is with JavaScript there are about nways to reimplement CSS features, and over time you can bet on every one of those ways being implemented with the end result being spaghetti code.
想象一个大型团队,其中每个开发人员都在重新创建 CSS 功能,例如:hover. 每个开发人员都会以不同的方式做这件事,随着团队规模的扩大,如果可以完成,就会完成。事实上,在 JavaScript 中,大约有n种方法可以重新实现 CSS 功能,随着时间的推移,您可以打赌实现这些方法中的每一种,最终结果都是意大利面条式代码。
So what to do? Use CSS. Granted you asked about inline styling going to assume you're likely in the CSS-in-JS camp (me too!). Have found colocating HTML and CSS to be as valuable as colocating JS and HTML, lots of folks just don't realise it yet (JS-HTML colocation had lots of resistance too at first).
那么该怎么办?使用 CSS。假设您询问了内联样式,您可能会在 CSS-in-JS 阵营中(我也是!)。发现将 HTML 和 CSS 并置与 JS 和 HTML 并置一样有价值,只是很多人还没有意识到(JS-HTML 共置一开始也有很多阻力)。
Made a solution in this space called Style Itthat simply lets your write plaintext CSS in your React components. No need to waste cycles reinventing CSS in JS. Right tool for the right job, here is an example using :after:
在这个空间中提出了一个名为Style It的解决方案,它可以让您在 React 组件中编写纯文本 CSS。无需浪费在 JS 中重新发明 CSS 的周期。正确工作的正确工具,这是一个使用示例:after:
npm install style-it --save
npm install style-it --save
Functional Syntax(JSFIDDLE)
函数式语法( JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return Style.it(`
#heart {
position: relative;
width: 100px;
height: 90px;
}
#heart:before,
#heart:after {
position: absolute;
content: "";
left: 50px;
top: 0;
width: 50px;
height: 80px;
background: red;
-moz-border-radius: 50px 50px 0 0;
border-radius: 50px 50px 0 0;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
-webkit-transform-origin: 0 100%;
-moz-transform-origin: 0 100%;
-ms-transform-origin: 0 100%;
-o-transform-origin: 0 100%;
transform-origin: 0 100%;
}
#heart:after {
left: 0;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
-webkit-transform-origin: 100% 100%;
-moz-transform-origin: 100% 100%;
-ms-transform-origin: 100% 100%;
-o-transform-origin: 100% 100%;
transform-origin :100% 100%;
}
`,
<div id="heart" />
);
}
}
export default Intro;
JSX Syntax(JSFIDDLE)
JSX 语法( JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return (
<Style>
{`
#heart {
position: relative;
width: 100px;
height: 90px;
}
#heart:before,
#heart:after {
position: absolute;
content: "";
left: 50px;
top: 0;
width: 50px;
height: 80px;
background: red;
-moz-border-radius: 50px 50px 0 0;
border-radius: 50px 50px 0 0;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
-webkit-transform-origin: 0 100%;
-moz-transform-origin: 0 100%;
-ms-transform-origin: 0 100%;
-o-transform-origin: 0 100%;
transform-origin: 0 100%;
}
#heart:after {
left: 0;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
-webkit-transform-origin: 100% 100%;
-moz-transform-origin: 100% 100%;
-ms-transform-origin: 100% 100%;
-o-transform-origin: 100% 100%;
transform-origin :100% 100%;
}
`}
<div id="heart" />
</Style>
}
}
export default Intro;
Heart example pulled from CSS-Tricks
从CSS-Tricks 中提取的心脏示例
回答by Raphael Pinel
You can use styled components.
您可以使用样式化组件。
Install it with npm i styled-components
安装它 npm i styled-components
import React from 'react';
import styled from 'styled-components';
const YourEffect = styled.div`
height: 50px;
position: relative;
&:after {
// whatever you want with normal CSS syntax. Here, a custom orange line as example
content: '';
width: 60px;
height: 4px;
background: orange
position: absolute;
bottom: 0;
left: 0;
},
const YourComponent = props => {
return (
<YourEffect>...</YourEffect>
)
}
export default YourComponent
回答by Peter W
Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):
取决于您是否只需要将几个属性设置为内联样式,您可以执行类似此解决方案的操作(并使您不必安装特殊包或创建额外元素):
https://stackoverflow.com/a/42000085
https://stackoverflow.com/a/42000085
<span class="something" datacustomattribute="">
Hello
</span>
.something::before {
content: attr(datascustomattribute);
position: absolute;
}
Note that the datacustomattributemust start with dataand be all lowercase to satisfy React.
请注意,datacustomattribute必须以data小写开头才能满足 React。
回答by Stuart Aitken
Not a direct answer to the question, but this may help those who are having trouble creating styleinformation using Typescript.
不是问题的直接答案,但这可能会帮助那些在style使用 Typescript创建信息时遇到问题的人。
I was getting an error telling me that the following was incorrect:
我收到一条错误消息,告诉我以下内容不正确:
let iconStyle = {
position: 'relative',
maxHeight: '90px',
top: '25%',
}
The error told me that "types of property 'position' are incompatible". I have no idea why.
该错误告诉我“属性'位置'的类型不兼容”。我不知道为什么。
I fixed this by adding a strict Typescript declaration, like so:
我通过添加一个严格的 Typescript 声明来解决这个问题,如下所示:
let iconStyle: CSSProperties = {
position: 'relative',
maxHeight: '90px',
top: '25%',
}
This works.
这有效。

