简体   繁体   English

使用 CSS 模块时如何传入 props

[英]How to Pass in Props When Using CSS Modules

I have a button component and using Tailwindcss framework and css modules for additional styling which looks like the following.我有一个按钮组件,并使用 Tailwindcss 框架和 css 模块进行附加样式,如下所示。 This works as I'm using template literal to pull in the red background styling.这是因为我使用模板文字来引入红色背景样式。

CSS Module: CSS 模块:

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

React Component:反应组件:

import styles from "./style.module.css"

const Button = props => {
  return (
    <button
      className={`text-white py-2 px-4 rounded ${styles.red}`}
    >
      Button
    </button>
  )
}

But what if I wanted the background to be flexible and receive props in order to determine background color?但是如果我想让背景灵活并接收道具以确定背景颜色怎么办? I was thinking something like the below but obviously doesn't work:我在想类似下面的事情,但显然不起作用:

<button
  className={`text-white py-2 px-4 rounded ${styles.`${props.bgColor}`}`}
>

Turns out, this is the correct syntax:事实证明,这是正确的语法:

<button
   className={`text-white py-2 px-4 rounded ${styles[props.bgColor]}`}
>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM