ant-design/components/radio/radio.tsx

72 lines
2.3 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
import RcCheckbox from 'rc-checkbox';
2016-01-21 22:45:21 +08:00
import classNames from 'classnames';
import RadioGroup from './group';
import RadioButton from './radioButton';
import { RadioProps, RadioChangeEvent } from './interface';
import { ConfigContext } from '../config-provider';
import RadioGroupContext from './context';
import { composeRef } from '../_util/ref';
2015-08-21 18:24:09 +08:00
interface CompoundedComponent
extends React.ForwardRefExoticComponent<RadioProps & React.RefAttributes<HTMLElement>> {
Group: typeof RadioGroup;
Button: typeof RadioButton;
}
const InternalRadio: React.ForwardRefRenderFunction<unknown, RadioProps> = (props, ref) => {
const context = React.useContext(RadioGroupContext);
const { getPrefixCls, direction } = React.useContext(ConfigContext);
const innerRef = React.useRef<HTMLElement>();
const mergedRef = composeRef(ref, innerRef);
const onChange = (e: RadioChangeEvent) => {
if (props.onChange) {
props.onChange(e);
}
if (context?.onChange) {
context.onChange(e);
}
};
const { prefixCls: customizePrefixCls, className, children, style, ...restProps } = props;
const prefixCls = getPrefixCls('radio', customizePrefixCls);
const radioProps: RadioProps = { ...restProps };
if (context) {
radioProps.name = context.name;
radioProps.onChange = onChange;
radioProps.checked = props.value === context.value;
radioProps.disabled = props.disabled || context.disabled;
2019-08-05 18:38:10 +08:00
}
const wrapperClassString = classNames(className, {
[`${prefixCls}-wrapper`]: true,
[`${prefixCls}-wrapper-checked`]: radioProps.checked,
[`${prefixCls}-wrapper-disabled`]: radioProps.disabled,
[`${prefixCls}-wrapper-rtl`]: direction === 'rtl',
});
2019-08-05 18:38:10 +08:00
return (
// eslint-disable-next-line jsx-a11y/label-has-associated-control
<label
className={wrapperClassString}
style={style}
onMouseEnter={props.onMouseEnter}
onMouseLeave={props.onMouseLeave}
>
<RcCheckbox {...radioProps} prefixCls={prefixCls} ref={mergedRef as any} />
{children !== undefined ? <span>{children}</span> : null}
</label>
);
};
const Radio = React.forwardRef<unknown, RadioProps>(InternalRadio) as CompoundedComponent;
Radio.displayName = 'Radio';
Radio.Group = RadioGroup;
Radio.Button = RadioButton;
Radio.defaultProps = {
type: 'radio',
};
export default Radio;