我可以在react中在屏幕上的多个位置重用组件的单个示例吗?

fgw7neuy  于 2023-03-24  发布在  React
关注(0)|答案(1)|浏览(93)

我有这个应用程序,我写的react-native,在那里我有这个屏幕,其中显示约50-100图像和一些与他们相关的行动按钮,包括一个弹出菜单(一个与他们每个人)。有没有一种方法,我可以使用相同的弹出菜单(相同的示例)的所有图像?

<View>
             // react-native-paper Card Component
               <Card style={styles.card}>
                <Card.Content style={styles.cardContent}>
                  <Card.Cover
                    style={{ height: 60, width: 60 }}
                    source={
                      item.avatar ||
                      (item.gender === 'male'
                        ? require('../../assets/male.jpeg')
                        : require('../../assets/female.jpeg'))
                    }
                  />
                  <Caption style={styles.title}>{item.name}</Caption>
                </Card.Content>
                <Card.Actions>
                  <Avatar.Text
                    style={{ backgroundColor: 'skyblue' }}
                    size={24}
                    label={`#${item.id}`}
                  />
                 // react-native-paper Menu Component
                 // can i somehow use a single component for all cards?
                  <Menu
                    visible={this.state.visible}
                    onDismiss={this._closeMenu}
                    anchor={
                      <IconButton
                        icon="menu"
                        theme={theme}
                        size={20}
                        onPress={() => console.log('Pressed')}
                      />
                    }
                  >
                    <Menu.Item onPress={() => {}} title="Item 1" />
                    <Menu.Item onPress={() => {}} title="Item 2" />
                    <Divider />
                    <Menu.Item onPress={() => {}} title="Item 3" />
                  </Menu>
                </Card.Actions>
              </Card>
                  .
                  .
          //same card multiple times
                  .
                  .
             </View>
vawmfj5a

vawmfj5a1#

您可以将Menu组件提取到您自己的自定义组件中,然后在您的卡片中重用它。这意味着您只需定义一次Menu,然后多次使用该组件(这将为每张卡片创建一个单独的Menu示例,相互独立)。
您也可以为Card组件做同样的事情,这意味着您不必多次定义相同的东西。(您在组件中定义的方法将只对该组件的示例执行不像上面的代码那样在全局级别上执行-例如,this._closeMenu只会为定义它的Menu示例执行)
在这里查看如何提取和重用组件-https://caster.io/lessons/react-native-extracting-and-writing-react-native-components

相关问题