React Native 之 CheckBox 组件

时间:2024-03-19 13:38:39

React Native 的组件中没有包含 CheckBox 组件。由于用到了所以在此总结一篇关于 CheckBox 组件的文章。

1、安装

$ npm i react-native-check-box --save

2、效果图

React Native 之 CheckBox 组件

3、代码

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,Image} from 'react-native';
import CheckBox from 'react-native-check-box'

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isOneChecked:false,
      isTwoChecked:false,
      isThreeChecked:false
    }
  }
  render(){
    return(
      <View style={styles.container}>
        <CheckBox
          style={styles.checkBox}
          onClick={()=>{
            this.setState({
              isOneChecked:!this.state.isOneChecked
            })
          }}
          isChecked={this.state.isOneChecked}
          rightText={'Java'}
          rightTextStyle = {styles.text}
          checkedImage = {<Image source = {require('./img/disable.png')} style = {styles.image}/>}
          unCheckedImage = {<Image source = {require('./img/enable.png')} style = {styles.image}/>}
        />

        <CheckBox
          style={styles.checkBox}
          onClick={()=>{
            this.setState({
              isTwoChecked:!this.state.isTwoChecked
            })
          }}
          isChecked={this.state.isTwoChecked}
          rightText={'Android'}
          rightTextStyle = {styles.text}
          checkedImage = {<Image source = {require('./img/disable.png')} style = {styles.image}/>}
          unCheckedImage = {<Image source = {require('./img/enable.png')} style = {styles.image}/>}
        />

        <CheckBox
          style={styles.checkBox}
          onClick={()=>{
            this.setState({
              isThreeChecked:!this.state.isThreeChecked
            })
          }}
          isChecked={this.state.isThreeChecked}
          rightText={'other'}
          rightTextStyle = {styles.text}
          checkedImage = {<Image source = {require('./img/disable.png')} style = {styles.image}/>}
          unCheckedImage = {<Image source = {require('./img/enable.png')} style = {styles.image}/>}
        />
        
      </View>
    )
  }
}

const styles = StyleSheet.create({
  
  container: {
    flex:1,
    flexDirection:'column',
    backgroundColor:'#f5f6f8'
  },

  checkBox:{
    backgroundColor:'white',
    height:56,
    marginTop:1,
    justifyContent:'center'
  },
  image:{
    marginLeft:16,
    width:24,
    height:24,
  },

  text: {
    fontSize:18,
    color:'#424242'
  }
});

其它属性,可以参考:react-native-check-box