import React from 'react'; import { View, StyleProp, ViewStyle } from 'react-native'; import Checkbox from './Checkbox'; import { useControllableValue } from '../hooks'; import type { CheckboxValueType, CheckboxOptionType } from './content'; import { GroupContext } from './content'; export interface CheckboxGroupProps { /** * group 样式 */ style?: StyleProp; /** * 整组失效 */ disabled?: boolean; /** * 默认选中的选项 */ defaultValue?: Array; /** * 指定选中的选项 */ value?: Array; /** * 变化时回调函数 */ onChange?: (checkedValue: Array) => void; /** * 指定可选项 */ options?: Array; /** * 子元素 */ children?: React.ReactNode; /** * 排列方向 * @default vertical */ direction?: 'vertical' | 'horizontal'; } const CheckboxGroup = React.forwardRef((props, ref) => { const { style, options = [], direction = 'vertical', ...restProps } = props; const [value = [], onChange] = useControllableValue>(props); let { children } = props; const [registeredValues, setRegisteredValues] = React.useState([]); const getOptions = () => options.map(option => { if (typeof option === 'string') { return { label: option, value: option, }; } return option; }); const cancelValue = (val: string) => { setRegisteredValues(prevValues => prevValues.filter(v => v !== val)); }; const registerValue = (val: string) => { setRegisteredValues(prevValues => [...prevValues, val]); }; // 切换复选框的状态 const toggleOption = (option: CheckboxOptionType) => { const optionIndex = value.indexOf(option.value); const newValue = [...value]; if (optionIndex === -1) { newValue.push(option.value); } else { newValue.splice(optionIndex, 1); } const opts = getOptions(); onChange?.( newValue .filter(val => registeredValues.indexOf(val) !== -1) .sort((a, b) => { const indexA = opts.findIndex(opt => opt.value === a); const indexB = opts.findIndex(opt => opt.value === b); return indexA - indexB; }) ); }; if (options && options.length > 0) { children = getOptions().map(option => ( {option.label} )); } return ( {children} ); }); CheckboxGroup.displayName = 'Checkbox.Group'; export default React.memo(CheckboxGroup);