如何在 flatlist 中反应本机的图像上设置 onError

How to set onError on images in react native inside flatlist

我有一个页面,其中列出了人员及其信息。我已经使用 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 中的图像执行此操作来处理我的情况。

我们可以创建一个单独的组件并在 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 代码

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