如何在react中添加作用域 css?

IT技术 javascript css reactjs create-react-app
2021-05-23 03:50:56

是否有scoped css与 Vue一样的 React 等价物,非常易于使用,无需大量重写?我可以只导入一个现有的 css 文件,并将其连接到一个组件,它就可以工作吗?

在 Vue 中,它就像

<style scoped src="./boxes.css"></style>

还有巴姆!您的 css 现在适用于您的组件。

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>
  }
}
4个回答

这里的每个答案都与 CSS module有关,但 Vue 中的作用域样式以另一种方式工作。

这里是<style scoped>在 Vue中工作的 React 库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] {}

https://facebook.github.io/create-react-app/docs/adding-a-css-modules-stylesheet

按钮.module.css

.error {
  background-color: red;
}

另一个样式表.css

.error {
  color: red;
}

按钮.js

import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet

class Button extends Component {
  render() {
    // reference as a js object
    return <button className={styles.error}>Error Button</button>;
  }
}

结果:与其他 .error 类名没有冲突

<!-- This button has red background but not red text -->
<button class="Button_error_ax7yz">Error Button</button>

据我所知,没有办法完全按照 Vue 的方式来做,但是有很多库可以做这种事情,这给了你很多选择,无论你喜欢什么工作。我个人的建议是情感

React 中没有类似的东西。3种常见的风格方式:

  1. 导入一个 css 文件,然后className像普通 HTML 一样使用=> 无需学习,只需添加一个import即可。
  2. CSS-in-js 库。我更喜欢styled-component- 这太棒了。
  3. 内联样式