首页 > 解决方案 > (重新)渲染多个图像的正确方法

问题描述

我正在尝试学习 React Native(使用 Expo)并遇到渲染问题。我有一个包含 52 个元素(x、y、宽度、高度)的数组,在 render() 中,这些元素被转换为 Pressable/Image 组合。当我导航到页面时,一切正常,但是一旦我触发重新渲染(onPress 甚至保存在 Visual Studio Code 中),大多数图像就会消失。只有第一张图像正确显示,对于所有其他图像,我只能看到蓝色背景(因此位置/大小/旋转仍然正确)。如果我执行另一个 onPress(或保存操作),所有元素都会再次正确显示。由于我有 Java 背景,这对我来说都是全新的。我在代码中犯了任何错误吗?任何帮助将不胜感激。


doSomething = (id) => {
    alert('test')
}

render() {
    return (
        <ImageBackground
             source={require('../assets/background.png')}
             style={{
                flex: 1,
             }}>
             ... // omitted
            <View style={{flex: 0.8 }}>
                {this.createElements()}
            </View>
            ...
    )
}

createElements() {
    const elements = [];
        for(let i = 0; i < 52; i++) {
            const AnimatedTouchable = Animated.createAnimatedComponent(Pressable);
            elements.push(
                <AnimatedTouchable // animation values/actions have been removed from styling attributes to find the render bug more easily
                    onPress ={() => {this.doSomething(i)}}
                    underlayColor="#fff"
                    style={{
                        position: "absolute",
                        top: this.state.points[i].y + '%',
                        left: this.state.points[i].x + '%',
                        width: ELEMENT_WIDTH,
                        height: ELEMENT_HEIGHT,
                    }}
                    key={'AnimatedTouchable' + i}
                >
                    <Animated.Image
                        source={require('../assets/someImage.png')}
                        style={{ width: ELEMENT_WIDTH, height: ELEMENT_HEIGHT, backgroundColor: 'blue', zIndex: 1 }}
                        resizeMode={"stretch"}
                    />
                </AnimatedTouchable>   
           )
        }
    return elements;
}

   

标签: imagereact-nativerendering

解决方案


推荐阅读