react native简单的活动开关

import React, {Component} from 'react';
import {StyleSheet, TouchableOpacity, Animated} from 'react-native';

class AtButton extends Component {

    constructor(props) {
        super(props);
        this.state = {
            state: !!props.state,
            anim: new Animated.Value(props.state ? 1 : 0),
        };
    }

    on(){
        Animated.timing(
            this.state.anim,
            {
                toValue: 1
            }
        ).start();
    }

    off(){
        Animated.timing(
            this.state.anim,
            {
                toValue: 0
            }
        ).start();
    }

    change() {
        this.setState({
            state: !this.state.state,
        })
    }
    
    shouldComponentUpdate(nextProps, nextState, nextContext) {
        if (nextState.state !== this.state.state) {
            nextState.state ? this.on() : this.off();
            return true;
        }
        else {
            return false;
        }
    }
    
    render() {
        return (
            <TouchableOpacity style={{alignItems: "center", flexDirection: "row"}} onPress={() => this.change()}>
                <Animated.View style={[styles.background, {
                    backgroundColor: this.state.anim.interpolate({
                        inputRange: [0, 1],
                        outputRange: ["#999999", "#ffc9c0"],
                    })
                }]}/>
                <Animated.View style={[styles.round, {
                    transform: [{
                        translateX: this.state.anim.interpolate({
                            inputRange: [0, 1],
                            outputRange: [0, 15],
                        })
                    }],
                    backgroundColor: this.state.anim.interpolate({
                        inputRange: [0, 1],
                        outputRange: ["#e0e0e0", "#fd846f"],
                    }),
                }]}/>
            </TouchableOpacity>
        );
    }
}

const styles = StyleSheet.create({
    round: {
        position: "absolute",
        width: 20,
        height: 20,
        borderRadius: 10,
    },
    background: {
        width: 35,
        height: 14,
        borderRadius: 7,
    },
});

export default AtButton;

猜你喜欢

转载自blog.csdn.net/weixin_41441644/article/details/84581019
今日推荐