使用按钮 React 创建 Div
Create Div using button React
我是 React App 的新手,我只想在每次单击按钮后创建 DIV,请帮忙。
import logo from './logo.svg';
import './App.css';
function App() {
function handleSubmit() {
let div = document.createElement('div');
div.innerText = document.getElementById('getText').innerText;
document.body.appendChild(div);
}
return (
<div className="App">
<header className="App-header">
<form onSubmit={handleSubmit}>
<button>Click me!</button>
<div id="getText"> INNER TEXT</div>
</form>
</header>
</div>
)}
export default App;
记录您点击按钮的次数 (count
)。然后你可以使用 for 循环来创建你需要添加的 div
的数量。
import { useState } from "react";
const divCreator = (total) => {
const divArray = [];
for (var i = 0; i < total; i++) {
divArray.push(
<div id="getText" key={i}>
INNER TEXT
</div>
);
}
return divArray;
};
function App() {
const [count, setCount] = useState(0);
function handleSubmit() {
setCount((state) => state + 1);
}
return (
<div className="App">
<header className="App-header">
<button onClick={handleSubmit}>Click me!</button>
{divCreator(count)}
</header>
</div>
);
}
export default App;
应用程序视图
我是 React App 的新手,我只想在每次单击按钮后创建 DIV,请帮忙。
import logo from './logo.svg';
import './App.css';
function App() {
function handleSubmit() {
let div = document.createElement('div');
div.innerText = document.getElementById('getText').innerText;
document.body.appendChild(div);
}
return (
<div className="App">
<header className="App-header">
<form onSubmit={handleSubmit}>
<button>Click me!</button>
<div id="getText"> INNER TEXT</div>
</form>
</header>
</div>
)}
export default App;
记录您点击按钮的次数 (count
)。然后你可以使用 for 循环来创建你需要添加的 div
的数量。
import { useState } from "react";
const divCreator = (total) => {
const divArray = [];
for (var i = 0; i < total; i++) {
divArray.push(
<div id="getText" key={i}>
INNER TEXT
</div>
);
}
return divArray;
};
function App() {
const [count, setCount] = useState(0);
function handleSubmit() {
setCount((state) => state + 1);
}
return (
<div className="App">
<header className="App-header">
<button onClick={handleSubmit}>Click me!</button>
{divCreator(count)}
</header>
</div>
);
}
export default App;
应用程序视图