【问题标题】:react-table render component inside datareact-table 在数据中渲染组件
【发布时间】:2020-01-12 14:32:46
【问题描述】:

我正在尝试使用 react-table 包 (https://www.npmjs.com/package/react-table#example) 在数据中添加一个组件

使用包自述文件中的示例,我正在尝试使用精美的组件将图像添加到单元格: 在代码中使用**跳出... 我也试过:

imageUrl:{<PlaceholderImage width={60} textColor="#fff" text="Image"/>}

示例:

import ReactTable from 'react-table'
import 'react-table/react-table.css'
**import { PlaceholderImage } from 'react-placeholder-image'**

render() {
  const data = [{
    name: 'Tanner Linsley',
    age: 26,
**imageUrl:<PlaceholderImage width={60} textColor="#fff" text="Image"/>,**
    friend: {
      name: 'Jason Maurer',
      age: 23,
    }
  },{
    ...
  }]

  const columns = [{
    Header: 'Name',
    accessor: 'name' // String-based value accessors!
  }, {
    Header: 'Age',
    accessor: 'age',
    Cell: props => <span className='number'>{props.value}</span> // Custom cell components!
  }, {
    Header: ' ',
    accessor: 'imageUrl', // String-based value accessors!
    maxWidth: 70,
    minWidth:70,
  },{
    id: 'friendName', // Required because our accessor is not a string
    Header: 'Friend Name',
    accessor: d => d.friend.name // Custom value accessors!
  }, {
    Header: props => <span>Friend Age</span>, // Custom header components!
    accessor: 'friend.age'
  }]

  return <ReactTable
    data={data}
    columns={columns}
  />
}

【问题讨论】:

    标签: reactjs react-table


    【解决方案1】:

    您正在将一个反应组件传递给一个需要字符串的数据字段。尝试通过Cell props 自定义您的单元格:

    const columns = [
      {
        Header: "Image",
        accessor: "imageUrl",
        maxWidth: 70,
        minWidth: 70,
        Cell: props => <PlaceholderImage width={60} textColor="#fff" text="Image" />
      }
    ];
    

    【讨论】:

    • 这里是 React-Table 的创建者和维护者...这是正确答案。
    • 如果我们想在后端生成这个怎么办?我们必须在 JSX 中定义列的任何地方。如果我们可以访问属性cell.column.attribute,我们可以按照自己的方式渲染它,但这似乎与该库的使用方式背道而驰..
    【解决方案2】:

    除了@Clarity 的回答之外,还可以在Cell 的属性级别访问单元格的值:

    const columns = [
      {
        Header: "Image",
        accessor: "imageUrl",
        maxWidth: 70,
        minWidth: 70,
        Cell: ({ cell: { value } }) => (
          <img
            src={value}
            width={60}
          />
        )
      }
    ];
    

    【讨论】:

    • 我喜欢这个答案...只是稍微修改一下,在 ({ cell: { value }) 中添加一个右大括号变成 ({ cell: { value }})
    猜你喜欢
    • 2018-08-04
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 2020-11-04
    相关资源
    最近更新 更多