在React中,可以使用泛型来解决“不可分配给类型IntrinsicAttributes & IntrinsicClassAttributes”的问题。
假设我们有一个组件MyComponent
,它接受一个名为props
的属性,并将其传递给一个内部的div
元素,代码如下:
import React, { PropsWithChildren } from 'react';
interface MyComponentProps {
className?: string;
}
const MyComponent: React.FC> = ({ className, children }) => {
return {children};
};
在这个示例中,我们使用了PropsWithChildren
泛型来解决类型错误。PropsWithChildren
是一个React内置的类型,它将children
属性添加到传递给组件的属性中。
使用PropsWithChildren
后,我们可以在组件中使用className
和children
属性,且不会出现类型错误。
希望以上解决方法对您有帮助!