前段时间一直在做 react native 开发, 下面介绍下自定义自定义 radio 的封装.
- import React, { PureComponent } from 'react';
- import PropTypes from 'prop-types';
- import { View, Text, StyleSheet, TouchableOpacity, Image, Dimensions } from 'react-native';
- import uniq from 'lodash/uniq';
- import includes from 'lodash/includes';
- import difference from 'lodash/difference';
- const selected = require('../images/programme/radioSelect.png')
- const unselected = require('../images/programme/radioUnSelect.png')
- export default class Radio extends PureComponent {
- handleSelect = (option, index) => {
- const { onSelect, type, value } = this.props
- const valueAfterSelected = toggleValue(option, type, value)
- onSelect && onSelect(valueAfterSelected, index)
- }
- render() {
- const { options, value, type } = this.props;
- return (
- <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
- {
- options.map((option, index) => (
- <View key={index} style={styles.main}>
- <TouchableOpacity onPress={() => this.handleSelect(option, index)}>
- <Image
- style={{
- marginLeft: 5,
- marginRight: 10,
- width: 15,
- height: 15,
- }}
- source={isSelected(option, type, value) ? selected : unselected}
- />
- </TouchableOpacity>
- <Text style={styles.text}>{option.label}</Text>
- </View>
- ))
- }
- </View>
- );
- }
- }
- function isSelected(option, type, value) {
- if (type === 'radio') {
- return option.value === value
- } else {
- return (value || []).includes(option.value)
- }
- }
- function toggleValue(option, type, value) {
- if (type === 'checkbox') {
- return !includes(value, option.value) ? uniq([...(value || []), option.value]) : difference(value, [option.value])
- } else {
- return option.value
- }
- }
- const { width } = Dimensions.get('window');
- const styles = StyleSheet.create({
- main: {
- flexDirection: 'row',
- marginLeft: width == 320 ? 8 : 10,
- marginRight: width == 320 ? 5 : 10,
- marginTop: 5,
- marginBottom: 5,
- justifyContent: 'flex-start',
- alignItems: 'center',
- },
- text: {
- marginLeft: 0,
- fontSize: 13,
- color: '#333',
- },
- });
- MoreRadio.propTypes = {
- type: PropTypes.string,
- options: PropTypes.array,
- }
- MoreRadio.defaultProps = {
- type: 'radio',
- }
单选
- <CustomRadio
- type="radio"
- onSelect={this.customRadio.bind(this)}
- options={[{ value: 1, label: '报备' }]}
- value={this.state.auditType}
- />
多选
- <CustomRadio
- type="checkbox"
- onSelect={this.customRadio.bind(this)}
- options={[{ value: 1, label: '报备' }, { value: 2, label: '审批' }]}
- value={this.state.productChannel}
- />
来源: http://www.bubuko.com/infodetail-2932370.html