【问题标题】:React: Render column component as a row component in a TableReact:将列组件呈现为表格中的行组件
【发布时间】:2018-01-30 11:31:45
【问题描述】:

我正在 React 中创建一个 Table 组件。我正在查看一些表格组件,它们创建了一个列数组以传递给表格。在此列数组中,您可以放置​​一个函数来在 tbody 的每一行内呈现一个组件。

Ant 设计的第一个示例 (https://ant.design/components/table/):

const columns = [{
  title: 'Name',
  dataIndex: 'name',
  key: 'name'
}, {
  title: 'Action',
  key: 'action',
  render: (text, record) => ( <<-- THIS FUNCTION. IT RECEIVES THE ROW RECORD AS A PARAM TOO
    <span>
      This gonna be rendered in each row of the table
    </span>
  ),
}];  

我正在尝试找出一种创建这种机制以在表格主体的每一行中呈现一列的好方法。

有什么好的例子可以学习吗?我正在尝试阅读 NPM 中某些组件的源代码。但很难理解。

感谢开发者!

【问题讨论】:

  • columns 指的是 thead 内容而不是 tbody>tr 内容
  • @stack26 是的.. 但我试图弄清楚这种机制是如何工作的。列中的渲染函数如何作为单元格行。

标签: javascript reactjs components antd


【解决方案1】:

这是一个基本示例,通常您的 Table 组件会收到 2 个道具:

  • 数据源,可以是对象数组
  • 列配置,包含属性名,函数的窍门就是javascript的函数式编程,可以接收render函数,用户可以实现自己的render逻辑。

例如。

const dataSource = [
    {
        id: 1,
        name: 'aaaa',
        age: 10
    },
    {
        id: 2,
        name: 'bbbb',
        age: 11
    },
    {
        id: 3,
        name: 'ccc',
        age: 12
    },
];

所以列配置如下:

const column = [
    {
        key: 'id',
        label: 'ID'
    },
    {
        key: 'name',
        label: 'Student Name'
    },
    {
        key: 'age',
        label: 'Student Age',
        render: (text, record) => {
            return `** ${text} **`; // just for decoration
        }
    }
]

表格组件将围绕数据源进行迭代,并在列配置的帮助下构建表格标签。

但是,您始终可以在循环逻辑中添加类似这样的内容:

   if (typeof render === 'function') {
        cell = <td key={key}>{render(item[key], item)}</td>  // call the render function and pass the data
   } else {
        cell = <td key={key}>{item[key]}</td> // else will just render it
   } 

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 2016-07-28
    • 1970-01-01
    • 2017-10-29
    • 2020-12-11
    • 2021-11-30
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多