之前一個(gè)小功能需要用到switch 這個(gè)控件, 后來(lái)發(fā)現(xiàn)這個(gè)控件在ios 和 android 的顯示差異挺大的烙丛, 而且android 偶爾會(huì)出現(xiàn)控件不展示的情況查辩,不知道大家有沒(méi)有同樣的問(wèn)題拍霜, 后來(lái)決定自己擼一個(gè)試試。代碼很平常萎馅,
import React, { Component } from 'react';
import { StyleSheet,Animated, TouchableOpacity} from 'react-native';
const styles = StyleSheet.create({
container: {
height: 30,
width: 50,
borderRadius: 15,
backgroundColor: '#32CDFF',
},
scaleBg:{
flex:1,
borderRadius: 15,
backgroundColor: '#E7E8EA',
},
toggleBtn: {
height: 28,
width: 28,
backgroundColor:'white',
borderRadius: 14,
position:'absolute',
top:1,
}
});
class Switch extends Component {
constructor(props) {
super(props);
this.state = {
toggleOn:false,
}
this.toggerPostion = new Animated.Value(1);
this.scaleBg = new Animated.Value(1);
}
componentDidMount(){
const {value } = this.props;
if(value ) {
this.setState({toggleOn:true})
Animated.timing(this.scaleBg,{toValue: 0.1,duration:400,}).start();
Animated.spring ( this.toggerPostion, {toValue: sceneScale* ( 50 - 29 ),},
).start();
}
}
toggleSwitch = ()=> {
const {onPress,useOnce,onValueChange} = this.props;
if(this.state.toggleOn && useOnce === undefined) {
this.setState({
toggleOn:false,
})
Animated.spring(this.toggerPostion,{toValue: 1,},).start();
Animated.timing(this.scaleBg,{toValue: 1, duration:400,}).start();
onValueChange(false);
} else {
this.setState({
toggleOn:true,
})
Animated.spring (this.toggerPostion,{toValue: sceneScale* ( 50 - 29 ),},).start();
Animated.timing(this.scaleBg,{toValue: 0.0,duration:400,}).start();
if(onPress){
setTimeout(()=>{onPress()},400);
}
onValueChange(true);
}
}
componentWillReceiveProps(nextProps){
if(this.props.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>
<Animated.View
style={[styles.toggleBtn , { left: this.toggerPostion }]}
></Animated.View>
</TouchableOpacity>
);
}
}
export default Switch;
控件的用法
this.state = {
toggle = 0;
}
setToggle = (switchValue) => {
this.setState({
toggle:switchValue,
})
<Switch
value={toggle}
onValueChange={(switchValue)=>this.setToggle(switchValue)}
/>
實(shí)現(xiàn)的方法比較直接裆泳, 就是控制在點(diǎn)擊的時(shí)候按鈕位置的變化,和背景的動(dòng)畫(huà)縮放. 效果如下
大家可以控件擴(kuò)充一下蹋凝, 實(shí)現(xiàn)大小鲁纠, 顏色, 甚至動(dòng)畫(huà)效果的自定義仙粱。