在 react js 中为每个组件隔离 css



我在create-react-app上构建我的反应应用程序。我想为每个组件提供本地 css。我计划使用css模块 但这些都是问题

如果我使用 css 模块

  • 我将不得不运行弹出命令
  • 我可以将 css 模块与 scss 文件一起使用吗?我在这样的 scss 中嵌套

这是我的 scss 文件之一

$scalel: 1.7vmin;
.navbar-side {
  position: absolute;
  background: rgba(255,255,255,0.15);
  width: 17 * $scalel;
  top: 6.2 * $scalel;
  padding-bottom: 2 * $scalel;
  .tessact-logo {
    width: 50%;
    height: 12 * $scalel;
    background: url('/public/images/logo.png');
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    margin-left: 25%;
  }
  .navbar-item {
    padding: 0.8 * $scalel;
    transition: all 0.2s ease;
    cursor: pointer;
    padding-left: 3 * $scalel;
    &:hover {
      background: rgba(255,255,255,0.15);
    }
    &.active {
      background: rgba(255,255,255,0.25);
    }
    .navbar-item-inside {
      display: none;
    }
  }
}

*How can use classname={style.navbar-item}? key is navbar-item is in nest.*

另外,如果我不想使用css模块,有什么办法吗?在其中一个项目中,我看到有人像这样隔离css

import c from './Reviews.styl'
<div className={c.container}>
                <ReviewSearch
                    assignIsOpen={this.state.assignIsOpen}
                    toggleAssign={this.toggleAssign}
                    selectedRows={this.props.selectedRows}
                    onSubmitProcess={this.onSubmitProcess}/>
                <ReviewTable
                    isLoading={this.props.isLoading}
                    items={this.props.list}
                    selectedRows={this.props.selectedRows}
                    onRowSelection={this.onRowSelection}
                    authToken={this.props.auth_token}
                    setCurrentItem={this.setCurrentItem}/>
            </div>

样式文件为

:local(.container)
    display block
    width 100%
.control-container
    display flex
    align-items center
    .control-label
        width 120px
    .control
        flex 1
    & + .control-container
        margin-top 30px

使用样式文件而不是 CSS。我喜欢这种方式,因为在这种情况下,没有必要在所有子div中使用style.classname。我怎样才能做到这一点?

自从提出这个问题以来,很多事情都发生了变化。创建反应应用程序已经有一段时间(自react-scripts@2.0.0以来(支持CSS模块SCSS开箱即用而无需弹出。

https://create-react-app.dev/docs/adding-a-css-modules-stylesheet

您所要做的就是将任何文件从somestyle.css重命名为 somestyle.module.css,它现在将表现为 css 模块。

您可以通过将 someStyle.scss 重命名为 somestyle.module.scss 以相同的方式使用 scss

我建议使用类名。它是一个库,您可以通过它从css文件将css导入到组件中,然后像下面这样使用它:

import styles from './your.css'
import cn from 'classnames/bind'
const cx  = cn.bind(styles)

<div className={cx('myDiv')}/>

CSS模块的支持已经为create-react-app制作了很长时间,它应该在2.0测试版(https://github.com/facebookincubator/create-react-app/issues/3815(

最新更新