2021SC@SDUSC
Radio 单选框
用法:
用于在多个备选项中选中单个状态。
与Select选择器:
和 Select 的区别是,Radio 所有选项默认可见,方便用户在比较中选择,因此选项不宜过多。
Radio/Radio.Button
参数说明类型默认值autoFocus自动获取焦点booleanfalsechecked指定当前是否选中booleanfalsedefaultChecked初始是否选中booleanfalsedisabled禁用 Radiobooleanfalsevalue根据 value 进行比较,判断是否选中any-Radio Methods
名称描述blur()移除焦点focus()获取焦点部分源码
首先来看interface.tsx 也就是接口
import * as React from 'react';
import { AbstractCheckboxGroupProps } from '../checkbox/Group';
import { AbstractCheckboxProps } from '../checkbox/Checkbox';
import { SizeType } from '../config-provider/SizeContext';
引入checkbox多选框及多选框组
export type RadioGroupButtonStyle = 'outline' | 'solid';
export type RadioGroupOptionType = 'default' | 'button';
RadioButton 的风格样式,目前有描边和填色两种风格
OptionType设置 Radio options 类型,默认是小圆点
export interface RadioGroupProps extends AbstractCheckboxGroupProps {
defaultValue?: any;
value?: any;
onChange?: (e: RadioChangeEvent) => void;
size?: SizeType;
onMouseEnter?: React.MouseEventHandler
onMouseLeave?: React.MouseEventHandler
name?: string;
children?: React.ReactNode;
id?: string;
optionType?: RadioGroupOptionType;
buttonStyle?: RadioGroupButtonStyle;
}
可以看到接口继承自checkbox/group
export interface RadioGroupContextProps {
onChange: (e: RadioChangeEvent) => void;
value: any;
disabled?: boolean;
name?: string;
}
上下文,用于传递数据
export interface RadioChangeEvent {
target: RadioChangeEventTarget;
stopPropagation: () => void;
preventDefault: () => void;
nativeEvent: MouseEvent;
}
stopPropagation() 方法防止调用相同事件的传播。
传播意味着向上冒泡到父元素或向下捕获到子元素。如果事件是可取消的,则 preventDefault() 方法会取消该事件,这意味着属于该事件的默认操作将不会发生。
注意:并非所有活动都可以取消。使用 cancelable 属性 来确定事件是否可取消。
Radio.tsx
React.useEffect(() => {
devWarning(!('optionType' in props), 'Radio', '`optionType` is only support in Radio.Group.');
}, []);
使用useEffect,可以直接在函数组件内处理生命周期事件。
将它简单地看作是在渲染之后执行副作用的一种方式。
const onChange = (e: RadioChangeEvent) => {
props.onChange?.(e);
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;
}
const wrapperClassString = classNames(
`${prefixCls}-wrapper`,
{
[`${prefixCls}-wrapper-checked`]: radioProps.checked,
[`${prefixCls}-wrapper-disabled`]: radioProps.disabled,
[`${prefixCls}-wrapper-rtl`]: direction === 'rtl',
},
className,
);
设置前缀、props已备使用
将class名存在wrapperClassString中用于渲染
return (
// eslint-disable-next-line jsx-a11y/label-has-associated-control
);
};
利用react的checkbox多选框实现效果
const Radio = React.forwardRef
Radio.displayName = 'Radio';
export default Radio;
Radio获得InternalRadio中的props,并最终返回,
等于把内部radio封装起来