我有两个数组,1 列和 2 行。我想按照代码中所示动态地将行数组数据添加到列数组中。目前,我已经在这些数组中获取了硬编码值,我有一个添加按钮。 实际上我想渲染带有下拉按钮的 n*n 矩阵。
我在添加按钮上定义了一种方法,并使用 for 循环将列数组推送到行数组。
import React, { Component } from "react";
import './Table.css';
export class Table extends Component {
constructor(props) {
super(props)
this.state = {
columns: ['state 1', 'state 2', 'state 3', 'state 4', 'state 5', ''],
emptyheader: [''],
rows: [
['state 1', 'state 2', 'state 3', 'state 4', '', ''],
['state 2', 'state 2', 'state 3', 'state 4', ' ', ''],
['state 3', 'state 2', 'state 3', 'state 4', ' ', ''],
['state 4', 'state 2', 'state 3', 'state 4', ' ', ''],
['state 5', 'state 2', 'state 3', 'state 4', ' ', '']
],
selectedTeam: ''
}
this.handleChange = this.handleChange.bind(this)
}
render() {
return (
<div>
<table align="center">
<tbody>
<tr>
{this.state.emptyheader.map((emptyheader, i) =>
<td >{emptyheader}</td>
)}
{this.state.columns.map((column, i) =>
<td >{column}</td>
)}
</tr>
{this.state.rows.map((row, i) =>
<tr key={i}>
{row.map((cell, i) =>
(i < 1) ? (
<td scope="row" key={i}>{cell}</td>
) : (
<td>
<select>
<option value="forward">Forward</option>
<option value="reverse">Reverse</option>
<option value="NA">NA</option>
</select>
</td>
)
)}
</tr>
)}
</tbody>
</table>
</div>
);
}
}
export default Table;
我想渲染n*n矩阵
最佳答案
你能展示一下你的handleChange
方法吗
我觉得应该是这样的
this.handleChange = (e) => {
let { rows } = this.state;
rows.push(newElement);
this.setState(rows);
}
关于javascript - 我想以以下格式动态添加数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57917541/