在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属性,且不会出现类型错误。
希望以上解决方法对您有帮助!