我的目标是使用ReactJS从行列表([1、2、3])和列列表([1、2])创建以下html表:
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
请参阅下面的我的React脚本,以及这里的my codepen,该脚本似乎不起作用
class Tbody extends React.Component {
constructor(props) {
super(props);
this.state = {
columns: [1, 2],
rows: [1, 2, 3]
};
}
renderCols() {
return (
{this.state.columns.map(col => <td key={col}> {col} </td>)}
);
}
renderRows(){
return (
{this.state.rows.map(row => <tr key={row}> {this.renderCols()} </tr>)}
);
}
render() {
return <tbody>{this.renderRows()}</tbody>;
}
}
class Table extends React.Component {
render() {
return (
<div>
<table>
<Tbody />
</table>
</div>
);
}
}
ReactDOM.render(<Table />, document.getElementById("root"));
答案 0 :(得分:2)
您的renderCols
和renderRows
方法返回 JSX 。而是从那里返回普通的JS对象,而删除那些{..}
。
class Tbody extends React.Component {
constructor(props) {
super(props);
this.state = {
cols: [1, 2],
rows: [1, 2, 3]
};
}
renderCols() {
return (
this.state.cols.map(col => <td key={col}>{col}</td>)
);
};
renderRows(){
return (
this.state.rows.map(row => <tr key={row}>{this.renderCols()}</tr>)
);
}
render() {
return <tbody>{this.renderRows()}</tbody>;
}
}
class Table extends React.Component {
render() {
return (
<div>
<table>
<Tbody />
</table>
</div>
);
}
}
ReactDOM.render(<Table />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>