gpt4 book ai didi

javascript - 如何在另一个中创建 react 元素?

转载 作者:行者123 更新时间:2023-12-01 00:47:03 25 4
gpt4 key购买 nike

我构建了一个 React 应用程序,但遇到了一个问题:如何根据 useState 在另一个 React 元素中创建 React 元素?

我创建了一个稍微简化的示例:

import React, { useState } from 'react';
import Square from './square';

function Chart(props) {

const [counter, setCounter] = useState(0);

function increment() {
setCounter++;
}

return (
<div>
<button onClick={increment()}>More squares</button>
<div className="container">
{
//I want to create as much <Square number={counter}/> as the value of counter
}
</div>
</div>
);
}

export default Chart;

最佳答案

创建它们的数组。例如:

function Chart(props) {
const [counter, setCounter] = useState(0);

function increment() {
setCounter(oldCounter => oldCounter + 1);
}

const squares = [];
for (let i = 0; i < counter; i++) {
squares.push(<Square number={i} key={i}/>)
}

return (
<div>
<button onClick={increment}>More squares</button>
<div className="container">
{squares}
</div>
</div>
);
}

关于javascript - 如何在另一个中创建 react 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57279747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com