using css modules in react how can I pass a className as a prop to a component

眉间皱痕 提交于 2021-02-06 10:18:26

问题


If I have a react component and I want to pass in a className, how do I do this with CSS Modules. It currently just gives the className but not the hash generated css module name which I would get for <div className={styles.tile + ' ' + styles.blue}>

Here is my Tile.js component

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;
}

So as you can see I initialize this Tile wrapper component as follows in my Author Tile, but I want to pass a color prop into the component:

AuthorTile.js

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

回答1:


From the docs:

Avoid using multiple CSS Modules to describe a single element. 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;
}

Then <div className={styles[this.props.color]} should do the job, e.g:

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>
}


来源:https://stackoverflow.com/questions/34035820/using-css-modules-in-react-how-can-i-pass-a-classname-as-a-prop-to-a-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!