Last active
March 17, 2021 09:03
-
-
Save KiligFei/f52268d29dca430af2a076a83743366c to your computer and use it in GitHub Desktop.
[开关 Switch] ReactNavite 实现 Ant Switch 开关 # ReactNavite
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component} from 'react'; | |
import {Animated, StyleSheet, TouchableOpacity} from 'react-native'; | |
const styles = StyleSheet.create({ | |
container: { | |
height: 30, | |
width: 50, | |
borderRadius: 15, | |
backgroundColor: '#3AC16C', | |
}, | |
scaleBg: { | |
flex: 1, | |
borderRadius: 15, | |
backgroundColor: '#E7E8EA', | |
}, | |
toggleBtn: { | |
height: 28, | |
width: 28, | |
backgroundColor: 'white', | |
borderRadius: 14, | |
position: 'absolute', | |
top: 1, | |
}, | |
}); | |
class HandSwitch extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
toggleOn: false, | |
value: 0, | |
}; | |
this.togglePostion = new Animated.Value(1); | |
this.scaleBg = new Animated.Value(1); | |
} | |
componentDidMount() { | |
const {value} = this.props; | |
if (value) { | |
this.setState({value, toggleOn: true}); | |
Animated.timing(this.scaleBg, {toValue: 0.1, duration: 400}).start(); | |
Animated.spring(this.togglePostion, {toValue: (50 - 29)}, | |
).start(); | |
} | |
} | |
toggleSwitch = () => { | |
const {onPress, useOnce, onValueChange} = this.props; | |
if (this.state.toggleOn && useOnce === undefined) { | |
this.setState({ | |
toggleOn: false, | |
value: 0, | |
}, () => { | |
Animated.spring(this.togglePostion, {toValue: 1}).start(); | |
Animated.timing(this.scaleBg, {toValue: 1, duration: 400}).start(); | |
onValueChange(false); | |
}); | |
} else { | |
this.setState({ | |
toggleOn: true, | |
value: 1, | |
}, () => { | |
Animated.spring(this.togglePostion, {toValue: (50 - 29)}).start(); | |
Animated.timing(this.scaleBg, {toValue: 0.0, duration: 400}).start(); | |
if (onPress) { | |
setTimeout(() => { | |
onPress(); | |
}, 400); | |
} | |
onValueChange(true); | |
}); | |
} | |
}; | |
componentWillReceiveProps(nextProps) { | |
if (this.state.value !== nextProps.value) { | |
console.log('receive ' + this.state.toggleOn + ' ' + this.state.value + ' ' + nextProps.value); | |
this.toggleSwitch(); | |
} | |
} | |
render() { | |
return ( | |
<TouchableOpacity style={[styles.container]} onPress={this.toggleSwitch} activeOpacity={1}> | |
<Animated.View style={[styles.scaleBg, {transform: [{scale: this.scaleBg}]}]}/> | |
<Animated.View style={[styles.toggleBtn, {left: this.togglePostion}]}/> | |
</TouchableOpacity> | |
); | |
} | |
} | |
export default HandSwitch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment