简体   繁体   中英

Ionic - react how to repeat component

I want to repeat my component for n times using react in ionic but i don't know how to that

for example in my Component.tsx i have:

import React from 'react';
import { IonCard, IonCardContent} from '@ionic/react';

const Component: React.FC = () => {
    return(
        <div>
            <IonCard>
                <IonCardContent>Hello From Ion Card</IonCardContent>
            </IonCard>
        </div>
    )
};

export default Component;

And in my App.tsx I have:

import { IonApp} from '@ionic/react';
import '@ionic/react/css/core.css';
import '@ionic/react/css/normalize.css';
import '@ionic/react/css/structure.css';
import '@ionic/react/css/typography.css';
import '@ionic/react/css/padding.css';
import '@ionic/react/css/float-elements.css';
import '@ionic/react/css/text-alignment.css';
import '@ionic/react/css/text-transformation.css';
import '@ionic/react/css/flex-utils.css';
import '@ionic/react/css/display.css';
import './theme/variables.css';

import Component from './Component';


const App: React.FC = () => (
  <IonApp className="ion">
    <div>
       {
        // I want to repeat this
      <Component />
       }
    </div>
  </IonApp>
);

export default App;

I'm new to typescript and react, I would be so happy if you help

Thanks

You need a loop. The best loop here is map :

const App: React.FC = () => (
  <IonApp className="ion">
    <div>
       {
         Array(5).fill(null).map((_, i) => (
           <Component key={i} />
         ))
       }
    </div>
  </IonApp>
);

Don't forget that repeated components need to have a unique key prop in the loop.

And please pay attention to .fill(null) . When you create an array using the Array function, it gets filled with empty values, and running .map method on it will fail. We have to fill it with a value (In this case null ) in order to make it iterable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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