简体   繁体   English

在 React 功能组件中返回一个 for 循环

[英]return a for loop in React functional component

I'm building my own invoice/estimate generator with React .我正在使用React构建自己的发票/估算生成器。

I want to have a number of lines "product" equivalent to my state.我想要多行等同于我的 state 的“产品”。

I wanted to do a loop and return my JSX .我想做一个loopreturn我的JSX But I have no error, but my line product appears once only, and my state is set to 2 .但是我没有错误,但是我的行产品只出现一次,我的 state 设置为2

Here is my try:这是我的尝试:

export default function ProductInformations(props: TProductInformations) {
    const [numberOfProducts, setNumberOfProducts] = useState<number>(2);

    const handleNumberOfProducts = (type: string) => {
        if (type === "add") return setNumberOfProducts(numberOfProducts + 1);
        if (type === "remove") return setNumberOfProducts(numberOfProducts - 1);
    };

    for (let i = 0; i <= numberOfProducts; i++) {
        return (
            // here is <p> with "price", "quantity", "name of the product"...
        );
    }
}

As the JSX is a bit long, I don't want to do a function that returns html and call the function in JSX.由于 JSX 有点长,我不想执行返回 html 的 function 并在 JSX 中调用 function。

Any idea why?知道为什么吗?

Either push to an array要么推送到一个数组

export default function ProductInformations(props: TProductInformations) {
    const [numberOfProducts, setNumberOfProducts] = useState<number>(2);

    const handleNumberOfProducts = (type: string) => {
        if (type === "add") return setNumberOfProducts(numberOfProducts + 1);
        if (type === "remove") return setNumberOfProducts(numberOfProducts - 1);
    };
    
    const products =[]
  
    for (let i = 0; i <= numberOfProducts; i++) {
        products.push(
            // here is <p> with "price", "quantity", "name of the product"...
        );
    }
  
    return <>{products}</>
}

or use map或使用map

export default function ProductInformations(props: TProductInformations) {
    const [numberOfProducts, setNumberOfProducts] = useState<number>(2);

    const handleNumberOfProducts = (type: string) => {
        if (type === "add") return setNumberOfProducts(numberOfProducts + 1);
        if (type === "remove") return setNumberOfProducts(numberOfProducts - 1);
    };
    
  
    return [...Array(numberOfProducts + 1)].map(() => /* here is <p> with "price", "quantity", "name of the product"... */)

}

Resources:资源:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM