(
(
{
variant = "default",
size = "md",
error = false,
label,
labelPosition = "right",
className,
radioClassName,
disabled,
...props
},
ref
) => {
const radioId = React.useId();
const renderRadio = () => (
);
const renderLabel = () => {
if (!label) return null;
return (
);
};
if (!label) {
return renderRadio();
}
return (
{labelPosition === "left" && renderLabel()}
{renderRadio()}
{labelPosition === "right" && renderLabel()}
);
}
);
Radio.displayName = "Radio";
/**
* RadioGroup - 单选按钮组
*/
export interface RadioGroupProps {
children: React.ReactNode;
name: string;
label?: string;
error?: string;
required?: boolean;
value?: string;
onChange?: (value: string) => void;
className?: string;
orientation?: "vertical" | "horizontal";
}
export function RadioGroup({
children,
name,
label,
error,
required,
value,
onChange,
className,
orientation = "vertical",
}: RadioGroupProps) {
// 为每个 Radio 注入 name 和 onChange
const enhancedChildren = React.Children.map(children, (child) => {
if (React.isValidElement(child)) {
const childProps = child.props as { value?: string; onChange?: (e: React.ChangeEvent) => void };
return React.cloneElement(child as React.ReactElement, {
name,
checked: value !== undefined ? childProps.value === value : undefined,
onChange: (e: React.ChangeEvent) => {
onChange?.(e.target.value);
childProps.onChange?.(e);
},
});
}
return child;
});
return (
{label && (
{label}
{required && *}
)}
{enhancedChildren}
{error &&
{error}
}
);
}