react native簡單的活動開關
阿新 • • 發佈:2018-11-28
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;