我正在尝试从React中的数据填充表,但是遇到了上述错误。
这是填表的函数:
let numberOfColumns = props.tabColumns.split(",").length;
let tableData = props.tabRows.split(",");
function generateRows(){
let r = ``;
for (let i=0; i<tableData.length/numberOfColumns; i++){
r =`${r}<tr>`;
for(let j=0; j<numberOfColumns; j++){
r = `${r}<td>${tableData[i*numberOfColumns+j]}</td>`;
}
r =`${r}</tr>`;
}
console.log(r);
return r;
}
这是表格:
<table>
<tbody>
<tr>
{props.tabColumns.split(",").map((column, index) => <th key={"column"+index}>{column}</th>)}
</tr>
{generateRows()}
</tbody>
</table>
数据:
tabColumns: "Name,Age,Occupation",
tabRows: "John,18,Student," +
"Miranda,23,Nurse," +
"Ashley,32,Telephonist," +
"Rose,28,Driver"
答案 0 :(得分:3)
除非确实需要,否则不要将React渲染与手动html构造混合使用。首先,它消除了使用React的好处。使用React渲染行!
function renderRow(tableData, numberOfColumns, i) {
const cells = [];
for (const j = 0; j < numberOfColumns; ++j) {
cells.push(<td>tableData[i*numberOfColumns+j]</td>);
}
return <tr>{cells}</tr>;
}
render() {
const rows = [];
for (let i = 0; i < tableData.length / numberOfColumns; ++i) {
rows.push(renderRow(tableData, numberOfColumns, i);
}
return (
<table>
<tbody>
<tr>
{props.tabColumns.split(",").map((column, index) => <th key={"column"+index}>{column}</th>)}
</tr>
{rows}
</tbody>
</table>
);
}
答案 1 :(得分:0)
正如人们提到的那样,generateRows返回一个字符串。为了获得所需的东西,我必须将此字符串传递给解析器(https://www.npmjs.com/package/html-react-parser),解析器会为我提供正确的输出。