离子 - 反应如何重复组件

Ionic - react how to repeat component

我想使用离子反应重复我的组件 n 次,但我不知道该怎么做

例如在我的 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;

在我的 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;

我是 typescript 和 React 的新手,如果你能帮助我我会很高兴

谢谢

你需要一个循环。这里最好的循环是 map:

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

不要忘记重复的组件需要在循环中有一个唯一的 key 属性。

并请关注.fill(null)。当您使用 Array 函数创建数组时,它会填充 empty 值,并且对它的 运行 .map 方法将失败。我们必须用一个值填充它(在本例中为 null)以使其可迭代。