如何为映射的对象元素赋予不同的样式?

How to give different styles to mapped object elements?

我的主应用视图

import React from "react";

import Col from 'react-bootstrap/Col';
import Card from 'react-bootstrap/Card';


import "./Village.module.css";

const VillageItem = ({ label, fields, className }) => {
  return (
        <Col xs={12} sm={12} md={4} lg={4}>
          <Card style={{ width: '18rem' }}>
            <Card.Header className={className}><h5>{label}</h5></Card.Header>
              <Card.Body>
                <Card.Text>
                  {fields.map((field) => (
                    <p>{field}</p>
                  ))}
                </Card.Text>
              </Card.Body>
            </Card>
          </Col>
  );
};

export default VillageItem;

我的数组文件 className

export default {
  0: {
    label: "Village 1 - Academia",
    fields: ["Research", "Publications", "Development"],
    className: "Academia"
  },
  1: {
    label: "Village 2 - Private",
    fields: ["Investment", "Partnership", "Advocacy"],
    className: "Private"
  },

  2: {
    label: "Village 3 - Public",
    fields: ["Governance", "Accountability", "Leadership"],
    className: "Public"
  },
};

文件:当我调用函数时。

import React from "react";
import VillageItem from "./VillageItem";
import villages from "./villages";
import styles from "./Village.module.css";

import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';

const VillageList = () => {
  const villagesArray = Object.values(villages);
  return (
    <div className={styles.villageBody}>
      <h3 className={styles.villageHeading}>Description here...</h3>
      <p className={styles.villageInfo}>
          info here....
      </p>
      <Container className={styles.container}>
        <Row>
          {villagesArray.map((village) => (
            <VillageItem key={village.label} {...village} />
          ))}
        </Row>
      </Container>
    </div>
  );
};

export default VillageList;

我正在与 react.js 和 bootstrap 合作进行 React。我想分别为每个项目设置样式,我添加了一个类名,但它有效但样式不起作用。可能是什么原因? CSS 文件已正确导入。还有什么可以阻止它显示我的样式表?

另外,请问有没有在map方法中给每一项添加样式的方法?

如果您使用的是 CSS 模块,则必须像这样导入文件:

import styles from "./Village.module.css";

然后您必须实际使用 css 文件中的类名,因此:

<Card.Header className={styles[className] } ><h5>{label}</h5></Card.Header>

styles[className] 正在使用您数组中的类名并尝试在您的 .module.css 文件中找到它。确保在您的 .module.css 文件中定义了 3 类,例如:

.Private{
    color: red;
}
.Public{
    color: green;
}
.Academia{
    color: blue;
}

然后它在我的项目中工作。