【问题标题】:React Native: renderItem component to Custom FlatList as a prop? (like Vue slots)React Native:renderItem 组件以 Custom FlatList 作为道具? (如 Vue 插槽)
【发布时间】:2021-03-08 22:36:18
【问题描述】:

我想要一个可重用的 FlatList 组件,基本上是一个包装器,我可以将自定义组件作为要渲染的项目传递,并且我想将此组件作为道具传递,这很容易在 vue..js 中使用 scoped/slots 完成.

有没有办法在 react native 中做到这一点?

<View style={{ flex:1 }}>
        <FlatList  style={{ width:'100%'}}  data={props.data} keyExtractor={item => item.id.toString()}
            renderItem={({ item, index }) => 
            <PropComponent item={item}></PropComponent>}
        />
    </View>

在上面的例子中,PropComponent 会像这样传递给 CustomFlatList:

<CustomFlatList>
     <PropComponent></PropComponent>
</CustomFlatList>
```

【问题讨论】:

  • 是的,它被称为 HOC,它的工作原理相同,您只需在自定义平面列表中传递 {children} 道具,就像您将插槽放在 vuejs 中的位置一样

标签: javascript reactjs react-native native


【解决方案1】:

这样使用

// CustomFlatList.js

const { ...rest } = props;

<View style={{ flex:1 }}>
        <FlatList  
           style={{ width:'100%'}}  
           data={props.data} 
           keyExtractor={item => item.id.toString()}
           {...rest}
        />
</View>

用法

itemView = ({ item, index }) => {
 return <PropComponent item={item} />
}

<CustomFlatList renderItem={itemView} /> 

【讨论】:

    猜你喜欢
    • 2020-10-29
    • 1970-01-01
    • 2021-02-06
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2021-11-02
    • 2020-01-05
    相关资源
    最近更新 更多