首页 > 解决方案 > 如何在平面列表中的本地反应中对图像设置 onError

问题描述

我有一个页面,在其中列出人员及其信息。我使用 Flatlist 来渲染我得到的 n 个数据以及分页。

<FlatList
    showsVerticalScrollIndicator={false}
    data={this.state.records}
    keyExtractor={(item) => String(item.ServiceRequestID)}
    renderItem={({ item }) => (
    <View>
    <ImageBackground
    source={{ uri: this.state.baseUserImagePath + item.ImagePath }}
    style={styles.image}
    imageStyle={{ borderRadius: h2p(48) }}
    />
    //other parts
    </View>
    )}
    onEndReached={()=>{//logic}}
    />

我希望为无法加载的图像加载默认用户图像(在我的情况下在本地服务器中删除)。所以,我想在图像背景中添加 onError 属性。对于单个图像,我可以使用

onError={() => {this.setState({ image: require('../../assets/user.png') });}}并使用source={this.state.image}

如何为 Flatlist 中的图像执行此操作以处理我的情况。

标签: reactjsreact-nativereact-native-flatlistimagebackground

解决方案


我们可以创建一个单独的组件并在 flatlist renderItem 函数中使用它。

像:

const FlatListComponent = props => {

    const [isError, setError] = useState(false)

    return (
        <View>
            <ImageBackground
              source={isError ? require('show-defaultImage') : { uri: props.image }}
              style={styles.image}
              imageStyle={{ borderRadius: h2p(48) }}
              onError{(e) => setError(true)}
             />
            //other parts
        </View>
    )

}

平面列表代码

<FlatList
    showsVerticalScrollIndicator={false}
    data={this.state.records}
    keyExtractor={(item) => String(item.ServiceRequestID)}
    renderItem={({ item }) => (
        <FlatListComponent 
             image={this.state.baseUserImagePath + item.ImagePath}
        />
    )}
    onEndReached={()=>{//logic}}
/>

推荐阅读