React CSS 模块无法连接

React CSS Module cant connect

我想在 1 个 React 组件上使用 2 类。它都有自己的模块css self。我检查了文件名和道具没有拼写错误,但 css 没有附加。

import React from "react";
import styles from "./Card.module.css";

const Card = (props) => {
    return (
        <div className={{...styles.Card, ...props.className}}>
            {props.children}
        </div>
    );
};

export default Card;

有人知道为什么吗?

道具 className 需要是一个字符串。为了有 2 classes 你需要连接它们。

文档:https://reactjs.org/docs/faq-styling.html

<div className={`${styles.Card} ${props.className}`}>
    {props.children}
</div>

如果你想改善这一点,你可以使用包 classnames,它被广泛用于有条件地为组件设置 class 名称。

https://www.npmjs.com/package/classnames

The classNames function takes any number of arguments which can be a string or object. The argument 'foo' is short for { foo: true }. If the value associated with a given key is falsy, that key won't be included in the output.

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'