如何在react中添加作用域CSS? [英] How to add scoped css in react?
问题描述
是否像Vue中的范围内的CSS
一样具有超级容易的React,而无需进行大量重写?
Is there a React equivalent of scoped css
as in Vue that's super easy to work with, without a bunch of re-writes? One which I can just import an existing css file, and hook it up to a component, and it just works?
在Vue中,我可以将其导入到现有的CSS文件中,并将其连接到组件上,然后就可以正常工作了?
In Vue, it's as easy as
<style scoped src="./boxes.css"></style>
还有Bam!现在,您的CSS的作用域就变成了您的组件。
And Bam! Your css is now scoped to your component.
React中是否有类似内容?像
// import the css file
import styles from "./boxes.css";
// hook it to a component, or using any other methods
@inject(styles)
class Boxes extends Component {
render(){
<div className='container'>
/* must support multiple classes out-of-the-box, unlike CSSModule where you have to
re-write into a super long array like className={[styles.box, styles.green, styles.large]} */
<div className='box green large'></div>
<div className='box red small'></div>
</div>
}
}
推荐答案
每个答案在这里是关于CSS模块的,但是Vue中的作用域样式以另一种方式起作用。
Every answer here is about CSS Modules, but scoped styles in Vue works another way.
这是React的库,其作用类似于< style scoped>
在Vue中: https://github.com/gaoxiaoliangz/react-scoped -css
Here the library for React that works like <style scoped>
in Vue: https://github.com/gaoxiaoliangz/react-scoped-css
输入:
import React from 'react'
import './Title.scoped.css'
const Title = props => {
return (
<h1 className="title">
<p>{props.children}</p>
</h1>
)
}
export default Title
输出:
<h1 class="title" data-v-hi7yyhx>
.title[data-v-hi7yyhx] {}
这篇关于如何在react中添加作用域CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!