javascript - 如何在 react 中添加作用域的CSS?

标签 javascript css reactjs create-react-app

是否有一个 React 等价于 Vue 中的 scoped css,它 super 容易使用,无需大量重写?我可以只导入一个现有的 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>
  }
}

最佳答案

这里的每个答案都是关于 CSS 模块的,但是 Vue 中的作用域样式以另一种方式工作。

这里的 React 库的工作方式类似于 <style scoped>在 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] {}

关于javascript - 如何在 react 中添加作用域的CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50849070/

相关文章:

javascript - 如何修复 validateDOMNesting(...) : <td> cannot appear as a child of <tbody>. 和列表中的每个 child 都应该有一个唯一的 "key" Prop

javascript - npx create-react-app 客户端给出此错误 "Cannot read properties of undefined (reading ' isServer')"

javascript - 如何在不修改全局 Function.prototype 的情况下创建函数的继承属性?

css - Bootstrap 底部粘性页脚与网站重叠

javascript - Chrome 5 中的日期格式

html - Firefox 中缺少表格边框

html - 滚动条导致 Microsoft Edge 中的表格未对齐

reactjs - 单击页面上任意位置时禁用覆盖

javascript - 如果图像响应,则获取图像的高度和宽度

javascript - 如何使用 useState 设置 friend ?