单击(),我想添加表行



我想在每次单击时添加行,但我的代码正在替换同一行。

还试图将if保持在addTable函数之外,但这对我不起作用

我尝试了许多解决方案,但都失败了。有人能在这里帮我吗?

我已经在下面添加了我的代码,请检查并告诉我。

import { useState } from "react";
import "./App.css";
const App = (props) => {
const [count, setCount] = useState(0);
var [items, setItems] = useState([]);
function addTable() {
setCount(count + 1);
if (count <= 10) {
setItems(
<tr>
<td>5 x {count}</td>
<td>{5 * count}</td>
</tr>
);
}
}
console.log(count);
return (
<>
<div className="button">
<button onClick={addTable}>
Click to generate Multiplication tables of 5{" "}
</button>
</div>
<table>
<thead>
<tr>
<th>Multiplication</th>
<th>Results</th>
</tr>
</thead>
<tbody>{items}</tbody>
</table>
</>
);
};
export default App;

好吧,你正在覆盖onChange中的项目,你需要附加到它:

setItems([
...items,
<tr>
<td>5 x {count}</td>
<td>{5 * count}</td>
</tr>
]);

但我可能会做的是:

import { useState } from "react";
import "./App.css";
const App = (props) => {
const [count, setCount] = useState(0);
var [counts, setCounts] = useState([]);
function addTable() {
setCount(count + 1);
if (count <= 10) setCounts([...counts, count]);
}
console.log(count);
return (
<>
<div className="button">
<button onClick={addTable}>
Click to generate Multiplication tables of 5{" "}
</button>
</div>
<table>
<thead>
<tr>
<th>Multiplication</th>
<th>Results</th>
</tr>
</thead>
<tbody>{counts.map((c) => (
<tr>
<td>5 x {c}</td>
<td>{5 * c}</td>
</tr>
)}</tbody>
</table>
</>
);
};
export default App;

当您调用setItems时,您将用新行替换当前状态。

我删除了将JSX添加到state的部分(并完全删除了该state(,并将其替换为两个值:当前时间表值和上限。

然后,新函数getRows有一个简单的循环,将JSX添加到数组中并返回。

(此外,当计数超过限制时,我禁用了该按钮,因此您无法再添加任何行。(

const { useState } = React;
const App = () => {

// New constants
const timesTable = 5;
const limit = 10;

// One state
const [count, setCount] = useState(0);

// The button updates the count
function updateCount() {
setCount(count + 1);
}
// And we have a simple loop to push the right
// number of rows into an array which is
// then returned
function getRows(count) {
const rows = [];
for (let i = 0; i < count; i++) {
rows.push(
<tr class="row">
<td>{timesTable} x {i}</td>
<td>{timesTable * i}</td>
</tr>
);
}
return rows;
}
return (
<div>
<div className="button">
<button
disabled={count > limit}
onClick={updateCount}
>Add row to {timesTable}x table
</button>
</div>
<table>
<thead>
<tr>
<th>Multiplication</th>
<th>Result</th>
</tr>
</thead>
<tbody>
{getRows(count)}
</tbody>
</table>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('react')
);
.button { margin-bottom: 1em; }
table { border-collapse: collapse; }
th { text-transform: uppercase; }
tr:nth-child(odd) { background-color: #efefef; }
td, th { padding: 4px 8px; }
td { border: 1px solid #dfdfdf; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

最新更新