React Native组件学习 Switch
2018-04-26 本文已影响123人
天方夜歌
小萌在百忙之中说一下小组件Switch,用法简单,属性也不多,可是在开发中也是离不了的组件,比如
- 是否接受推送
- 是否开启省流量模式
等等诸如此类。
Switch 属性
属性 | 类型 | 描述 |
---|---|---|
disabled | bool | 默认false,如果为true,这个组件不能进行交互。 |
onValueChange | function | 当值改变的时候调用此回调函数,参数为新的值。 |
testID | string | 用来在端到端测试中定位此视图 |
value | bool | 表示此开关是否打开。默认为false(关闭状态)。 |
onTintColor | ColorPropType | 开启状态时的背景颜色。 |
thumbTintColor | ColorPropType | 开关上圆形按钮的背景颜色。 |
tintColor | ColorPropType | 关闭状态时的边框颜色(iOS)或背景颜色(Android)。 |
测试代码:
import {
Platform,
StyleSheet,
Text,
View,
Image,
Dimensions,
Switch,
} from 'react-native';
export default class MyPage extends Component {
constructor(props) {
super(props);
this.state = {
isOn:false,
};
}
render() {
return (
<View style={styles.container}>
{/*--------------------------Switch-------------------------------*/}
<Switch
// disabled={true}//是否可以响应,默认为false,true是无法点击
onTintColor='blue' //开关打开时的背景颜色
thumbTintColor='yellow' //开关上原形按钮的颜色
tintColor='black' //关闭时背景颜色
//当状态值发生变化值回调
// onValueChange={() => this.setState({isOn: !this.state.isOn})}
value={this.state.isOn == true}//默认状态
onValueChange={(e) => this.switchValue(e)} 当状态值发生变化值回调
/>
</View>
);
}
switchValue(e) {
alert(e);
this.setState(
{
isOn: e,
}
);
}
}
const styles = StyleSheet.create({
container: {
marginTop:30,
alignItems:'center'
},
});
效果:
