我想在React Native上为backgroundCarousel设置动画,但不知道如何制作动画

时间:2020-01-15 06:03:16

标签: javascript reactjs react-native

我想在reactNative中为该图像轮播设置动画,但不知道如何开始。阅读有关动画的文档,但仍然很困惑,不知道如何将其合并。我尝试过这种方法,但始终遇到严重的错误。救命!

import React from 'react';
import {StyleSheet, View, ScrollView, Dimensions, Image, Animated} from 'react-native'

const DEVICE_WIDTH = Dimensions.get('window').width;

class BackgroundCarousel extends React.Component {
    scrollRef = React.createRef();
    constructor(props) {
        super(props);

        this.state = {
            selectedIndex: 0,
            opacity: new Animated.Value(0)
        };
    }

    componentDidMount = () => {
        Animated.timing(this.state.opacity , {
            toValue: 1,
            duration: 500,
            useNativeDriver: true,
        }).start();
        setInterval(() => {
            this.setState(
                prev => ({ selectedIndex: prev.selectedIndex === 
                    this.props.images.length - 1 ? 0 : prev.selectedIndex +1 }),
            () => {
                this.scrollRef.current.scrollTo({
                    animated: true,
                    y: 0,
                    x: DEVICE_WIDTH * this.state.selectedIndex
                });
            }
            );
        }, 6000);

    };



    componentWillUnmount() {
        clearInterval(this.setState);
    }

    render() {
        const {images} = this.props
        const {selectedIndex} = this.state
        return (
            <Animated.Image
                onLoad={this.onLoad}
                {...this.props}
                style={[
                    {
                    opacity: this.state.opacity,
                    },
                    this.props.style,
                ]}
            />
            <View style= {{height: "100%", width: "100%"}}>
                {this.props.children}
                <ScrollView 

                horizontal 
                pagingEnabled
                scrollEnabled={false}
                ref={this.scrollRef}
                >
                    {images.map(image => (
                        <Image
                            key={image}
                            source={image}
                            style={styles.backgroundImage}
                        />
                    ))}
                </ScrollView>
            </View>
        )
    }
}

const styles = StyleSheet.create ({
    backgroundImage: {
        height: '100%',
        width: DEVICE_WIDTH,
    }

});

export default BackgroundCarousel;

任何帮助将不胜感激。不知道我要去哪里错了。基本上是尝试在背景轮播在图像之间变化时添加淡入淡出效果。

0 个答案:

没有答案