【问题标题】:Alternating Background Color react-bootstrap-table交替背景颜色反应引导表
【发布时间】:2018-07-02 22:38:38
【问题描述】:

我正在使用 react-bootstrap-table 并且我正在尝试更改背景颜色。该文档有点不清楚具体是什么类型的数据进入了条件渲染功能的实现,因此我无法收到正确的结果。我做错了什么?

// Customization Function 
function rowClassNameFormat(row, rowIdx) {
  // row is whole row object
  // rowIdx is index of row
  return rowIdx % 2 === 0 ? 'backgroundColor: red' : 'backgroundColor: blue';
}

// Data
var products = [
  {
    id: '1',
    name: 'P1',
    price: '42'
  },
  {
    id: '2',
    name: 'P2',
    price: '42'
  },
  {
    id: '3',
    name: 'P3',
    price: '42'
  },
];

// Component
class TrClassStringTable extends React.Component {
  render() {
    return (
      <BootstrapTable data={ products } trClassName={this.rowClassNameFormat}>
          <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
          <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
          <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
      </BootstrapTable>
    );
  }
}

【问题讨论】:

  • trClassName 允许您自定义赋予每个tr 的类。然后,您可以使用常规 CSS 为这些类设置任何您喜欢的样式。
  • 是的@Tholle,但我正在尝试进行“条件”格式化,所以我也需要 JS 逻辑。另外,我更在寻找 JS 样式的实现
  • 是的,JS 逻辑几乎可以像你已经拥有的代码一样,除了类名。 rowIdx % 2 === 0 ? 'bg-red' : 'bg-blue';,然后对它们进行样式设置。我不确定您是否可以有条件地自定义内联样式。

标签: javascript reactjs react-bootstrap-table


【解决方案1】:

您可以使用trStyle 而不是trClassName 自定义内联样式。内联样式也应该以对象形式返回,而不是作为字符串。

示例

function rowStyleFormat(row, rowIdx) {
  return { backgroundColor: rowIdx % 2 === 0 ? 'red' : 'blue' };
}

class TrClassStringTable extends React.Component {
  render() {
    return (
      <BootstrapTable data={ products } trStyle={rowStyleFormat}>
          <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
          <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
          <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
      </BootstrapTable>
    );
  }
}

【讨论】:

  • 首先,感谢您的回复!但是我运行了代码,它根本没有改变背景颜色。
  • @RyanCocuzzo 不客气。这很令人沮丧。我用一个工作的 CodeSandbox 更新了答案。你能看一下,看看你的代码是否不同?
  • 嗨@Tholle 我试过这个解决方案,不幸的是rowrowIdxrowStyleFormat 中都没有定义,看来trStyle 没有正确地通过对象...跨度>
  • @chutium 这令人沮丧。您可以查看official example 并查看您的代码是否匹配。
猜你喜欢
  • 2011-10-13
  • 2014-06-17
  • 1970-01-01
  • 2018-06-23
  • 2019-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多