简体   繁体   English

你如何在反应中传递动态 css 类?

[英]How do you pass dynamic css classes in react?

I have an image where the CSS class on the image needs to be change dynamically.我有一个图像,其中图像上的 CSS class 需要动态更改。 It is passed in dynamically from this object from the key "size":它是从这个 object 从键“size”动态传入的:

export const decals = [
  { label: 'Nikola Tesla', img: `/images/decals/tesla.svg`,  size: `decalMed` },
  { label: 'Tattoo Mom Heart', img: `/images/decals/ARF149.svg`, size: `decalSm`} 

Into another component here:在这里进入另一个组件:

import styles from ./Shirt.module.css';
<img key={decals[decal].label} src={decals[decal].img} alt={decals[decal].label} className={`${styles}.${decals[decal].size}`}/> 

The className= is the issue. className= 是问题所在。 I've tried so many different ways to pass this class.我尝试了很多不同的方法来传递这个 class。

I've captured this (decals[decal].size) into a variable before passing to the image tag.在传递给图像标签之前,我已将此 (decals[decal].size) 捕获到一个变量中。 I've tried to use the style tag instead of className and created a variable to hold the class.我尝试使用样式标签而不是 className,并创建了一个变量来保存 class。 I've changed around the brackets.我已经改变了括号。 I've tried passing it into an outside div.我试过将它传递给外部 div。

Nothing seems to work.似乎没有任何效果。

I'm wondering if anyone can clue a react newbie in. Thank you!我想知道是否有人可以找到反应新手。谢谢!

if I am not wrong, you trying to dynamically manage classes that are passing through to the image element.To do that, I recommend you to use "classnames" https://www.npmjs.com/package/classnames如果我没记错的话,您尝试动态管理传递给图像元素的类。为此,我建议您使用“类名” https://www.npmjs.com/package/classnames

With this package, you can control classNames with variables in your component.使用此 package,您可以使用组件中的变量控制类名。 I will try explain usage with a little example.我将尝试用一个小例子来解释用法。

Your style file like你的样式文件像

.yourParentClass {
    &.decalMedClass {
        // your styles for this class
    }
    &.decalSmClass {
        // your styles for this class
    }
}

your component file like你的组件文件像

import Style from '../style.scss';   // Your classes
var classNames = require('classnames/bind');  // classname package
const cx = classNames.bind(Style);

// your code
render() {
    return (
        <img className={
            cx({
                yourParentClass: true,
                decalMedClass: this.state.sizeMed,
                decalSmClass: !this.state.sizeMed,
            })
        }
        />
    );
}

Basically, you telling that which class gonna be active.基本上,您告诉哪个 class 将处于活动状态。 Please do not stick with my example, there are good examples on the npm page.请不要拘泥于我的例子,npm 页面上有很好的例子。

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

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