1. 程式人生 > >RN Animated做個畫線的動畫

RN Animated做個畫線的動畫

RN小白,剛學一個禮拜,專案中需要這個效果,感覺挺好玩,分享出來。話不多說直接上程式碼~

import React, {Component} from 'react'
import {Text, Animated, Easing, StyleSheet, View} from 'react-native'

class LinePlus extends Component {

    constructor(props) {
        super(props);
        this.state = {
            offset: new Animated.Value(this.props.startOffset || 200),
        }
        this.toValue = this.props.toValue || 0;
        this.duration = this.props.duration || 800;
        this.delay = this.props.delay || 0;
        this.easing = this.props.easing || Easing.ease;
    }

    componentDidMount() {
        this.startAnimated();
    }

    startAnimated = (callback=()=>{}) => {
        Animated.timing(this.state.offset, {
            toValue: this.toValue,
            duration: this.duration,
            delay: this.delay,
            easing: this.easing 
        }).start(() => {
            callback();
        });
    }

    render() {
        return (
            <View style={{
                width: this.props.startOffset || 200,
                height: 2,
                backgroundColor: '#242424',
                marginLeft: 50,
                marginTop: 50,
            }}>
                <Animated.View style={{
                    width: this.state.offset,
                    height: 2,
                    backgroundColor: '#FFFFFF',
                }}>
                    <View></View>
                </Animated.View>
            </View>
        );
    }
}

class LineMinus extends Component {

    constructor(props) {
        super(props);
        this.state = {
            offset: new Animated.Value(this.props.startOffset || 0),
        }
        this.toValue = this.props.toValue || 200;
        this.duration = this.props.duration || 800;
        this.delay = this.props.delay || 0;
        this.easing = this.props.easing || Easing.ease;
    }

    componentDidMount() {
        this.startAnimated();
    }

    startAnimated = (callback=()=>{}) => {
        Animated.timing(this.state.offset, {
            toValue: this.toValue,
            duration: this.duration,
            delay: this.delay,
            easing: this.easing 
        }).start(() => {
            callback();
        });
    }

    render() {
        return (
            <Animated.View style={{
                width: this.state.offset,
                height: 2,
                backgroundColor: '#242424',
                marginLeft: 50,
                marginTop: 50,
            }}>
            <View></View>
            </Animated.View>
        );
    }
}

export {
    LineMinus,
    LinePlus
}

const styles = StyleSheet.create({
    
});

效果如下:背景色可以設定,反方向也可以,拓展下也能做個簡單的進度條~