mh-rn-component
Version:
124 lines (119 loc) • 3.52 kB
Flow
import React, { useState, useEffect } from 'react'
import { View, Text, TextInput, ScrollView, StyleSheet, StyleProp, ViewStyle } from 'react-native';
import Checkbox from '../Checkbox'
import renderNode from '../helpers/renderNode'
type Options = {
label: string,
value: string
}
type Props = {
checked: string[],
onChange: (value: string[]) => void,
children?: any,
options?: Options[],
name?: string,
disabled?: boolean,
activeIcon?: React.ReactElement<{}>,
inactiveIcon?: React.ReactElement<{}>,
rightIcon?: boolean,
checkedColor?: string,
style?: StyleProp<ViewStyle>;
iconSize?: number
}
/**
* todo 目前先用any保证运行
*/
const CheckboxGroup = React.forwardRef<any, Props>(({ checked, onChange, options, ...rest }: Props, ref) => {
const [_value, setValue] = useState<string[]>(checked)
const [_optionsAll, setOptionsAll] = useState<string[]>([])
const checkRadio = (val: string) => {
const _have = _value.includes(val)
setValue((prev) => {
if (_have) {
prev.splice(prev.indexOf(val), 1)
} else {
prev.push(val)
}
return [...prev]
})
onChange(_value)
}
useEffect(() => {
let _optionsValueAll: string[] = []
options && options.map((item: Options) => {
_optionsValueAll.push(item.value)
})
rest.children && React.Children.toArray(rest.children).map((child: any) => {
_optionsValueAll.push(child?.props.value)
})
setOptionsAll([..._optionsValueAll])
}, [])
const toggleAll = (status: boolean | null) => {
/**
* 全选和取消全选
*/
if (typeof status === 'boolean') {
if (status) {
setValue([..._optionsAll])
onChange(_optionsAll)
} else {
setValue([])
onChange([])
}
} else {
// 取反
let reverseArr: string[] = []
_optionsAll.map(item => {
if (!_value.includes(item)) {
reverseArr.push(item)
}
})
setValue([...reverseArr])
onChange(reverseArr)
}
}
const root = React.useRef<any>(null);
React.useImperativeHandle(ref, () => {
const input = root.current;
if (input) {
return {
toggleAll: toggleAll,
};
}
const noop = () => {
throw new Error('Checkbox is not available');
};
return {
toggleAll: noop,
};
});
return (
<View style={rest.style} ref={root}>
<>
{options && options.map((item, index) => {
return (
<Checkbox onPress={checkRadio} checked={_value.includes(item.value)} key={index} {...item} {...rest}></Checkbox>
)
})}
{rest.children && (
React.Children.toArray(rest.children).map((child: any) => {
return React.cloneElement(child as React.ReactElement<any>, {
onPress: checkRadio,
checked: _value.includes(child?.props.value),
name: rest.name,
disabled: child?.props.disabled || rest.disabled,
activeIcon: child?.props.activeIcon || rest.activeIcon,
inactiveIcon: child?.props.inactiveIcon || rest.inactiveIcon,
rightIcon: child?.props.rightIcon || rest.rightIcon,
checkedColor: child?.props.checkedColor || rest.checkedColor,
children: child?.props.children,
iconSize: child?.props.iconSize || rest.iconSize,
})
})
)
}
</>
</View>
)
})
export default CheckboxGroup