React 确实有类似于 Vue 3 中 $attrs 的概念,但实现方式略有不同。
我们需要一种方法来处理那些未在 Props 中明确定义的额外属性。React 确实没有像 Vue 3 的 $attrs 那样的内置概念,但我们可以通过一些技巧来实现类似的功能。以下是几种可能的解决方案:
- 使用 rest 参数和展开运算符:
interface Props {
specificProp: string;
}
const MyComponent: React.FC<Props> = ({ specificProp, ...rest }) => {
return <div {...rest}>{specificProp}</div>;
};
// 使用
<MyComponent specificProp="value" className="extra-class" data-custom="custom" />
这种方法会将所有未在 Props 中定义的属性收集到 rest
对象中。
- 使用泛型扩展 HTMLAttributes:
interface Props extends React.HTMLAttributes<HTMLDivElement> {
specificProp: string;
}
const MyComponent: React.FC<Props> = ({ specificProp, ...rest }) => {
return <div {...rest}>{specificProp}</div>;
};
这种方法允许组件接受所有有效的 HTML 属性,同时还可以定义自己的特定属性。
- 创建一个自定义 hook 来分离 props:
function useExtraProps<T extends object, K extends keyof T>(props: T, keys: K[]): [Pick<T, K>, Omit<T, K>] {
const picked = {} as Pick<T, K>;
const omitted = {} as Omit<T, K>;
Object.keys(props).forEach(key => {
if (keys.includes(key as K)) {
picked[key as K] = props[key as K];
} else {
omitted[key as keyof Omit<T, K>] = props[key as keyof Omit<T, K>];
}
});
return [picked, omitted];
}
interface Props {
specificProp: string;
}
const MyComponent: React.FC<Props & React.HTMLAttributes<HTMLDivElement>> = (props) => {
const [myProps, extraProps] = useExtraProps(props, ['specificProp']);
return <div {...extraProps}>{myProps.specificProp}</div>;
};
这个自定义 hook 允许你明确地分离出已定义的 props 和额外的 props。
- 使用 TypeScript 的 Omit 类型:
interface Props {
specificProp: string;
}
type ExtraProps = Omit<React.HTMLAttributes<HTMLDivElement>, keyof Props>;
const MyComponent: React.FC<Props & ExtraProps> = ({ specificProp, ...rest }) => {
return <div {...rest}>{specificProp}</div>;
};
这种方法使用 TypeScript 的类型系统来明确定义额外的 props。
这些方法都允许你在已经定义了 Props 的情况下,仍然能够接收和处理额外的属性。选择哪种方法主要取决于你的具体需求和代码风格偏好。无论选择哪种方法,都能实现类似 Vue 3 $attrs 的功能,允许父组件传递额外的属性到子组件。