React的Css In Js怎么写伪元素样式

例如实现如下CSS

.box {
    width: 300px;
    height: 300px;
}

.box::before {
    content: 'Hello';
    color: red;
}

box的样式应该是这样

const styles = {
    box: {
        width: '300px',
        height: '300px'
    }
}

这种Css in Js写法能够写伪元素样式吗,如果可以应该怎么写呢。

阅读 20.4k
3 个回答

使用styled-components 或者 radium
使用radium写法如下:

var styles = {
  base: {
    color: '#fff',

    // Adding interactive state couldn't be easier! Add a special key to your
    // style object (:hover, :focus, :active, or @media) with the additional rules.
    ':hover': {
      background: color('#0074d9').lighten(0.2).hexString()
    }
  }
}

CSS in JS是不支持伪元素的写法的,你必须把伪元素替换成真实元素,你举的这个例子实现类似下面:

render() {
    <div>
      <span style={{color:'red'}}>Hello</span>   //真实元素
      <span style={styles.box}>World</span> 
    </div>
}

不过对于 ::placeholder 和 ::selection,CSS in JS 是无法实现的,对于 ::first-letter 和::first-line,则需要很繁琐的js代码才可实现。

var styles = {
base: {

color: '#fff',
&:hover: {
  background: xxxx
}

}
}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题