【问题标题】:using css modules in react how can I pass a className as a prop to a component在反应中使用css模块如何将className作为道具传递给组件
【发布时间】:2016-03-06 06:51:30
【问题描述】:

如果我有一个 react 组件并且我想传入一个类名,我该如何使用 CSS 模块来做到这一点。它目前只给出了 className 而不是我会得到的散列生成的 css 模块名称 <div className={styles.tile + ' ' + styles.blue}>

这是我的 Tile.js 组件

import React, { Component } from 'react';

import styles from './Tile.css';

class Tile extends Component {

  render() {

    return (
      <div className={styles.tile + ' ' + this.props.color}>
        {this.props.children}
      </div>
    );
  }
};

export default Tile;

Tile.css

@value colors: "../../styles/colors.css";
@value blue, black, red from colors;

.tile {
    position: relative;
    width: 100%;
    padding-bottom: 100%;
}

.black {
  background-color: black;
}

.blue {
  background-color: blue;
}

.red {
  background-color: red;
}

如您所见,我在 Author Tile 中按如下方式初始化此 Tile 包装器组件,但我想将颜色道具传递给组件:

AuthorTile.js

return (
  <Tile orientation='blue'>
   <p>{this.props.title}</p>
   <img src={this.props.image} />
  </Tile>
);

【问题讨论】:

    标签: css reactjs webpack-style-loader css-modules css-loader


    【解决方案1】:

    来自文档:

    避免使用多个 CSS 模块来描述单个元素。 https://github.com/gajus/react-css-modules#multiple-css-modules

    @value colors: "../../styles/colors.css";
    @value blue, black, red from colors;
    
    .tile {
        position: relative;
        width: 100%;
        padding-bottom: 100%;
    }
    
    .black {
        composes: tile;
        background-color: black;
    }
    
    .blue {
        composes: tile;
        background-color: blue;
    }
    
    .red {
        composes: tile;
        background-color: red;
    }
    

    然后&lt;div className={styles[this.props.color]} 应该完成这项工作,例如:

    render: function(){
      // ES2015
      const className = styles[this.props.color];
    
      // ES5
      var className = '';
    
      if (this.props.color === 'black') {
        className = styles.black;
      }
    
      return (
        <div className={className}>
          {this.props.children}
        </div>
    }
    

    【讨论】:

    • 你如何建议这个Tile组件有多种颜色背景,可以在初始化的时候定义?
    • 你所做的并不是一个使用 css 模块组合的坏方法,但我仍然主要关心的是如何为 Tile 使用颜色通道,例如&lt;Tile color='black'&gt; 这在 Tile 中是如何翻译的? &lt;div className={this.props.color}&gt; 不会工作,因为它期望 {styles.blue} 而不是 blue 会变成类似 components_Tile__blue__abc5436
    • 如果你使用 ES2015 &lt;div className={styles[this.props.color]} 应该可以完成这项工作。如果没有,只需检查 this.props.color 值,例如 var className = ''; if (this.props.color === 'black') { className = styles.black; }
    • &lt;div className={styles[this.props.color]} 做到了。你太棒了,如果你回答这个问题,我可以将其标记为已接受。我实际上想过这样做,但第一次弄乱了语法。谢谢
    • 如果我使用的是 ES5 或 6 并且我有例如10 个类名,我是否必须检查所有类名才能创建正确的 styles.x ?没有更好的办法解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2017-01-31
    • 2017-08-17
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多