react表迭代对象数组以打印列中的值

IT技术 reactjs
2021-05-09 00:03:58

我正在使用 react-table 生成表格(https://react-table.js.org/#/story/readme)。我有一个状态定义如下:

this.state = {

    sampleTable:[
        {author: 'Mac', books: [{title:'One', price: 20}, {title:'Two', price: 20}]},
        {author: 'Rick', books: [{title:'Three', price: 20}, {title:'Four', price: 20}]}
    ],

    sampleTableColumns:[
        {Header: 'Author', accessor: 'author'},
        {Header: 'Books', accessor: 'books.title'},
    ],
};

我正在尝试制作如下表格:

<ReactTable
    className="-highlight"
    data={this.state.sampleTable}
    columns={this.state.sampleTableColumns}
    defaultPageSize={10}
/>

但是在书籍栏中我什么也没看到。我不确定我应该如何迭代书籍数组,以便我可以在书籍列中打印书名?

4个回答

我必须像下面这样编写我的访问器:

sampleTableColumns:[
    {
        Header: 'Author',
        accessor: 'author',

    },
    {
        Header: 'Books',
        id:'books',
        accessor: data => {
            let output = [];
            _.map(data.books, book => {
                output.push(book.title);
            });
            return output.join(', ');
        },
    },
],

这很简单,无需使用任何依赖项,例如 lodash ...

你只需要使用 React-table Cell属性

sampleTableColumns:[
{
    Header: 'Author',
    accessor: 'author',
},
{
    Header: 'Books',
    accessor: 'books',
    Cell: (props) => {
        const { sampleTable} = props.original;
        return (
            { sampleTable.books.map( (book) =>(<h4>{book.title}</h4>)) }
        );
    },
},],

您的books数据是一个数组,我不相信react-table默认情况下如何呈现这些数据。您可以改为在该单元格的 sampleTableColumns 中提供您自己的渲染函数,它看起来像:

sampleTableColumns:[
    {Header: 'Author', accessor: 'author'},
    {
      Header: 'Books', 
      accessor: 'books'
      render: (rowInfo) => {
        return (
          <span>
           {rowInfo.value.map(book => (<span>{book.title}</span>))}
          </span>
      },
    },
],

好吧,我参加聚会为时已晚,但以上所有内容对我都不起作用,我尝试使用 ES6 语法。我已经请求了数组中的数据,所以我们开始(我重命名了变量):

  export const returnPreparedField = (array) => {
    const newArray = [];

    for (let arrayValue of array) {

        const newElement = {
            id: "element",
            header: element,
            accessor: data => data.element.find(elementToFind => (elementToFind.name === element))?.value,
            show: true,
            width: 100
        };

        newArray.push(newElement);
    }
    return newArray;
};