【问题标题】:How to set onError on images in react native inside flatlist如何在平面列表中反应原生的图像上设置 onError
【发布时间】:2021-05-25 10:53:12
【问题描述】:

我有一个页面,可以列出人员及其信息。我已经使用 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={() =&gt; {this.setState({ image: require('../../assets/user.png') });}} 并使用source={this.state.image}

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

【问题讨论】:

    标签: reactjs react-native react-native-flatlist imagebackground


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多