1. 第三方组件的安装
GitHub:https://github.com/crazycodeboy/react-native-check-box
在ReactNative工程的命令行下安装
npm i react-native-check-box –save
2. 本地控件的封装
2.1 import和常量定义,可根据工程自行调整
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
StyleSheet,
View,
Text,
Image,
} from 'react-native';
import CheckButton from 'react-native-check-box';
import { setSpText, scaleSize } from './../core/screen-util';
import { textFontSize, textColor } from './../config/genericStyle';
const ICON_CHECKED = require('./../../image/icon_checkedbox.png');
const ICON_UNCHECKED = require('./../../image/icon_uncheckedbox.png');
2.2 组件代码
所用到的样式自行添加,可以支持左侧文本和右侧文本,目前为右侧文本
export default class CheckBox extends Component {
constructor(props) {
super(props);
}
onClick(data) {
data.checked = !data.checked;
this.props.onClick(data);
}
renderRightText(data) {
return (<Text style={styles.rightText}>{data.text}</Text>);
}
render() {
let data = this.props.data;
return (
<CheckButton
style={{ padding: scaleSize(8) }}
onClick={() => this.onClick(data)}
isChecked={data.checked}
rightTextView={this.renderRightText(data)}
checkedImage={<Image source={ICON_CHECKED} style={styles.image} />}
unCheckedImage={<Image source={ICON_UNCHECKED} style={styles.image} />}
/>);
}
}
3. Demo
使用当前封装的CheckBox组件,必备参数如下
简单的例子:
...
import CheckBox from './../../lib/component/checkbox';
...
onChecked(data) {
console.log('click : ' + JSON.stringify(data));
}
render() {
let data = [{ 'text': 'testcheckbox', 'checked': false }, { 'text': 'checkbox2', 'checked': false }];
return (
<View style={{ flexDirection: 'row' }}>
<CheckBox data={data[0]} onClick={this.onChecked.bind(this, data[0])} />
<CheckBox data={data[1]} onClick={this.onChecked.bind(this, data[1])} />
</View>
);
}
...