简体   繁体   English

如何循环反应

[英]How to loop in react

How to loop for repeating如何循环重复

This is my code这是我的代码

This is App.js这是 App.js

import React from 'react';
import './App.css';
import Child from './Child/Child';

function App() {
  return (
    <div className="container">
      <div className='row'>
        <Child></Child>
      </div>
    </div>
  );
}

export default App;

This is Child.js这是 Child.js

import React from 'react';
import './Child.css';

function Child() {
    return(
        <div className='container'>
            <div className='row'>
                <h1>Mark</h1>
            </div>
        </div>
    )
}

export default Child

If I am not clear with my doubt, please put a comment.如果我不清楚我的疑问,请发表评论。

To loop n number of times, you can map over an array of length n and return your component.要循环n次,您可以map长度为n的数组并返回您的组件。

function App() {
  const n = 10;
  return (
    <div className="container">
      <div className='row'>
        {[...Array(n)].map((_, index) => (
           <Child key={index} />
        ))}
      </div>
    </div>
  );
}

You could just put ten Child components into an array and render that.您可以将十个子组件放入一个数组中并进行渲染。

const children = []
for(let i = 0; i < 10; i++){
  children.push(<Child key={i}/>)
}
  return (
    <div className="container">
      <div className='row'>
        {children}
      </div>
    </div>
  );

https://reactjs.org/docs/lists-and-keys.html#rendering-multiple-components https://reactjs.org/docs/lists-and-keys.html#rendering-multiple-components

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

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