import React, { useEffect, useMemo, useState } from 'react' import withDefaults from '../utils/with-defaults' import { RadioContext } from './radio-context' import { NormalSizes } from '../utils/prop-types' interface Props { value?: string | number initialValue?: string | number disabled?: boolean size?: NormalSizes onChange?: (value: string | number) => void className?: string useRow?: boolean } const defaultProps = { disabled: false, size: 'medium' as NormalSizes, className: '', useRow: false } type NativeAttrs = Omit, keyof Props> export type RadioGroupProps = Props & typeof defaultProps & NativeAttrs export const getRadioSize = (size: NormalSizes): string => { const sizes: { [key in NormalSizes]: string } = { mini: '12px', small: '14px', medium: '16px', large: '18px' } return sizes[size] } const RadioGroup: React.FC> = ({ disabled, onChange, value, size, children, className, initialValue, useRow, ...props }) => { const [selfVal, setSelfVal] = useState(initialValue) const updateState = (nextValue: string | number) => { setSelfVal(nextValue) onChange && onChange(nextValue) } const providerValue = useMemo(() => { return { updateState, disabledAll: disabled, inGroup: true, value: selfVal } }, [disabled, selfVal]) const fontSize = useMemo(() => getRadioSize(size), [size]) const groupGap = `calc(${fontSize} * 1)` useEffect(() => { if (value === undefined) return setSelfVal(value) }, [value]) return (
{children}
) } export default withDefaults(RadioGroup, defaultProps)