我使用'react-virtualized'来创建表格。在该表中,一些数据可能显示为'<b>Brian Vaughn1</b>'
。此表格单元格应为font-weight: bold
,并且只应呈现文本,不带标签。像这样:
我已经设法通过使用ReactDOM.findDOMNode
来解决这个问题(我应该避免这样做),但我认为应该有更好,更清晰的方法来做到这一点。
这是我的代码:
import React, { Component } from 'react';
import { Column, Table } from 'react-virtualized';
import './chart-table.scss';
class ChartRTable extends Component{
constructor(props){
super(props);
this.handleScroll = this.handleScroll.bind(this);
}
getColumns(data){
const columnsNumber = data.namesForColumns.length;
const columnWidth = this.props.tableWidth / columnsNumber;
let namesForColumns = ['name', 'description'];
return namesForColumns.map( name => {
return (
<Column
label={name}
dataKey={name}
width={columnWidth}
/>
)
})
}
handleScroll(){
// not a very nice way to make use of <b> tags in data
let dom = ReactDOM.findDOMNode(this);
let all = dom.getElementsByClassName('ReactVirtualized__Table__rowColumn');
let texts = [].slice.call(all).filter( (text) => text.innerHTML.indexOf('<') > -1);
texts.map( (el) => {
let text = el.innerHTML;
let newText = text.replace(/<b>/g, '').replace(/<\/b>/g, '');
el.innerHTML = newText;
el.style.fontWeight = 'bold';
})
}
componentDidMount(){
this.handleScroll();
}
render() {
// dummy data
const list = [
{ name: 'Brian Vaughn', description: '<b>Software engineer1</b>' },
{ name: 'Brian Vaughn', description: 'Software engineer' },
{ name: '<b>Brian Vaughn1</b>', description: 'Software engineer' },
{ name: 'Brian Vaughn', description: 'Software engineer' },
{ name: 'Brian Vaughn', description: 'Software engineer' },
{ name: 'Brian Vaughn', description: 'Software engineer' },
{ name: '<b>Brian Vaughn</b>', description: '<b>Software engineer</b>' },
{ name: 'Brian Vaughn', description: 'Software engineer' },
{ name: 'Brian Vaughn', description: 'Software engineer' },
{ name: 'Brian Vaughn', description: 'Software engineer' },
{ name: 'Brian Vaughn', description: 'Software engineer' },
{ name: 'Brian Vaughn', description: 'Software engineer' },
];
return(
<Table
onScroll={this.handleScroll}
ref='table'
width={this.props.tableWidth}
height={this.props.tableHeight}
headerHeight={35}
rowHeight={37}
rowCount={list.length}
rowGetter={({ index }) => list[index] }
>
{this.getColumns(this.data)}
</Table>
)
}
};
//TODO PropTypes
export default ChartRTable;
有什么想法吗?
答案 0 :(得分:2)
有点奇怪,看到我自己的名字贴满了StackOverflow问题。 :)
执行此操作的最佳方法是使用自定义columnRenderer
,就像我在示例here中所做的那样。因此,在上述情况下,您可以删除handleScroll
并将getColumns
替换为以下内容:
getColumns(data){
const columnsNumber = data.namesForColumns.length;
const columnWidth = this.props.tableWidth / columnsNumber;
let namesForColumns = ['name', 'description'];
return namesForColumns.map( name => {
return (
<Column
label={name}
dataKey={name}
width={columnWidth}
cellRenderer={
({ cellData, columnData, dataKey, rowData, rowIndex }) => {
const shouldHighlight = cellData.indexOf('<b>') === 0
const text = cellData.replace(/<\/*b>/g, '')
return shouldHighlight
? <strong>{text}</strong>
: text
}
}
/>
)
})
}