简体   繁体   English

离子 - 反应如何重复组件

[英]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我想在 ionic 中使用 react 重复我的组件 n 次,但我不知道该怎么做

for example in my Component.tsx i have:例如在我的Component.tsx我有:

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:在我的App.tsx中,我有:

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我是 typescript 的新手并做出反应,如果你能提供帮助,我会很高兴

Thanks谢谢

You need a loop.你需要一个循环。 The best loop here is map :这里最好的循环是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.不要忘记重复的组件在循环中需要有一个唯一的key prop。

And please pay attention to .fill(null) .请注意.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.当您使用Array function 创建数组时,它会被empty值填充,并且在其上运行.map方法将失败。 We have to fill it with a value (In this case null ) in order to make it iterable.我们必须用一个值填充它(在本例中为null )以使其可迭代。

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

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