如何在react-table中为单个列展示多组数据?
嘿,我来帮你搞定这个需求!首先先提个小细节:你代码里的product写成数组[]了,其实应该是对象{}(因为每个条目里的product是单个的name+description组合,不是列表),不然会触发语法错误哦~
接下来就是配置columns的核心部分,有两种常用方式实现同一列展示name和description:
方式一:用accessor直接拼接文本
这种方式适合简单的文本展示,直接返回拼接后的字符串:
render(){ const { data } = this.state; const columns = [ { Header: 'ID', accessor: 'id' }, { Header: 'Keyword', accessor: 'keyword' }, { Header: 'Product Info', // 目标列的表头 // 直接拼接name和description,用换行符分隔 accessor: row => `${row.product.name}\n${row.product.description}` } ]; return ( <div className="app-body"> <ReactTable data={data} columns={columns} /> </div> ) }
方式二:用Cell自定义JSX(更推荐)
如果想给name加样式(比如加粗)、给description换行展示,或者更灵活的布局,就用Cell属性自定义渲染内容:
render(){ const { data } = this.state; const columns = [ { Header: 'ID', accessor: 'id' }, { Header: 'Keyword', accessor: 'keyword' }, { Header: 'Product Info', // 解构获取当前行数据,自定义渲染结构 Cell: ({ row }) => ( <div className="product-info"> <strong>{row.product.name}</strong> <p style={{ marginTop: '4px', marginBottom: 0 }}> {row.product.description} </p> </div> ) } ]; return ( <div className="app-body"> <ReactTable data={data} columns={columns} /> </div> ) }
记得先把getInitialState里的product从数组改成对象,修正后的state代码:
getInitialState(){ return { data: [{ id: 1, keyword: 'Example Keyword', product: { name: 'Red Shoe', description: 'This is a red shoe.' } },{ id: 2, keyword: 'Second Example Keyword', product: { name: 'blue shirt', description: 'This is a blue shirt.' } }] } },
这样就能完美实现同一列同时展示名称和描述啦~
内容的提问来源于stack exchange,提问作者user42010
相关产品推荐
相关产品推荐

