[英]CSS Pseudo-classes with inline styles in react.js
现在具有背景的示例文本将是红色。 但我希望类rightElement:在使用border-top:color之后。 它应该来自const。 我不知道该怎么做
const color = "red";
<div className='rightElement' style={{backgroundColor: color} >Example </div>
rightElement:after
{
border-top :color ( From const color )
}
你在找这个:? ( https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties )
:root { --my-color: red; } .rightElement { display: inline-block; border-top :5px solid var(--my-color); }
<div class="rightElement" > Example </div>
请参阅React中的CSS伪元素 。 似乎最佳实践是在React中使用单独的元素而不是伪元素。 你可以这样做吗?
<div className='rightElement' style={{backgroundColor: color}}>
Example
<div style={{borderTopColor: color}}></div>
</div>
无法直接访问伪元素。
但是,您可以通过添加包含新规则的新样式元素来间接更改其样式。
尝试这样在css之后添加。
const color = "red"; var styleElem = document.head.appendChild(document.createElement("style")); styleElem.innerHTML = "#rightElement:after {border-top: 1px solid "+color+";}";
<div id='rightElement' style="background-color: green" >Example </div>
在HTML和CSS中
.testAfter::after { content: "->" }
<div class="testAfter">Something</div>
我们可以在css中使用:: after和其他伪代码。
所以我们需要外部css来反应中使用伪代码。
// test.css
.rightElement::after { content: "-> after"; border-top: 1px solid red; }
// Test.js
import React from 'react'; import './test.css'; class Test extends React.Component { render () { const color = "red"; return( <div> <div className='rightElement' style={{backgroundColor: color}} >Example </div> </div> ) } } export default Test;
使用内联
render () { const color = "red"; return( <div style={{width: '500px', margin: '0 auto', marginTop: '100px'}}> <div className='rightElement' style={{backgroundColor: color}} >Example </div> <div style={{borderTop: `10px solid ${color}`}}></div> </div> ) }
这里的技巧是在我创建新元素之前通过:: after或::创建新元素的瞬间。 但是只为造型目的创造新元素并不好(仅限我的选择)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.