【问题标题】:Apply modifier class to specified items in an array [React]将修饰符类应用于数组中的指定项 [React]
【发布时间】:2018-06-14 13:52:45
【问题描述】:
head: {
    className: '',
    columns: ['Name', 'Title', 'Position', 'Company'],
    center: true,
  },

cp-table-head--center {
  text-align: center;
}
  • 以上是我在 React 中用于表格组件的 Javascript。
  • 下面是修饰符对应的 CSS

有谁知道我如何将修饰符仅应用于数组中的某些头部项目?谢谢。

【问题讨论】:

  • 你是怎么渲染的?

标签: javascript css arrays reactjs sass


【解决方案1】:

我建议使用“classnames”包在 React 中应用 BEM,因为向组件添加条件类/修饰符要容易得多。但要回答你的问题,我可能会这样做:

import React from 'react';
import classnames from 'classnames';

const TableHead = ({ title, center = false }) => {
  const styling = classnames({
    'cp-table-head': !center,
    'cp-table-head--center': center,
  });

  return <th className={styling}>{title}</th>
}

const Table = () => {
  const columns = ['Name', 'Title', 'Position', 'Company'];
  const headers = columns.map((title) => (
    <TableHead key={title} title={title} center />
  ));

  return (
    <table>
      <thead>
        <tr>
          {headers}
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>body..</td>
        </tr>
      </tbody>
    </table>
  )
}

这个例子比较简单,所以你可以选择只使用三元运算符:

className={`cp-table-head${center ? '--center' : ''}`}

要回答有关将特定标题项居中的问题。您可以将上述TableHead 组件与...一起使用:

...
const Table = () => {
  const columns = [
    {
      title: 'Name',
      center: true,
    },
    {
      title: 'Title',
      center: false,
    },
    {
      title: 'Position',
      center: true,
    },
    {
      title: 'Company',
      center: false,
    }
  ];

  const headers = columns.map((header, index) => (
    <TableHead key={index} title={header.title} center={header.center} />
  ));
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-05
    • 2013-01-05
    • 2023-04-06
    • 2016-09-21
    • 2022-01-09
    • 1970-01-01
    • 2011-06-25
    • 2018-08-12
    相关资源
    最近更新 更多