React 组件上的 Typescript 错误 "children does not exists on type IntrinsicAttributes & RefAttributes<unknown>'.* "
Typescript error "children does not exists on type IntrinsicAttributes & RefAttributes<unknown>'.* " on react component
错误:
输入'{ children: string;严重性:字符串; sx: { 宽度: 字符串; }; }' 不可分配给类型 'IntrinsicAttributes & RefAttributes'。
属性 'children' 在类型 'IntrinsicAttributes & RefAttributes' 上不存在。
警报组件
const Alert = React.forwardRef(function Alert(props, ref) {
const ref_var = useRef<HTMLDivElement>(null);
return <MuiAlert elevation={6} ref={ref_var} variant="filled" {...props} />;
});
使用警报组件
<Alert severity="success" sx={{ width: "100%" }}>
Success
</Alert>
自定义Alert组件实现是正确的,但是你必须提到React.forwardRef
的道具React.forwardRef<HTMLDivElement, AlertProps>
来解决TypeScript编译问题。
此外,不需要本地 ref
变量 ref_var
。
const AlertFixed = React.forwardRef<HTMLDivElement, AlertProps>(
(props, ref) => (
<MuiAlert elevation={6} ref={ref} variant="filled" {...props} />
)
);
并调用 Alert
组件,
<AlertFixed severity="error" sx={{ width: "50%" }}>
Failed
</AlertFixed>
这是工作 codesanbox。
错误:
输入'{ children: string;严重性:字符串; sx: { 宽度: 字符串; }; }' 不可分配给类型 'IntrinsicAttributes & RefAttributes'。 属性 'children' 在类型 'IntrinsicAttributes & RefAttributes' 上不存在。
警报组件
const Alert = React.forwardRef(function Alert(props, ref) {
const ref_var = useRef<HTMLDivElement>(null);
return <MuiAlert elevation={6} ref={ref_var} variant="filled" {...props} />;
});
使用警报组件
<Alert severity="success" sx={{ width: "100%" }}>
Success
</Alert>
自定义Alert组件实现是正确的,但是你必须提到React.forwardRef
的道具React.forwardRef<HTMLDivElement, AlertProps>
来解决TypeScript编译问题。
此外,不需要本地 ref
变量 ref_var
。
const AlertFixed = React.forwardRef<HTMLDivElement, AlertProps>(
(props, ref) => (
<MuiAlert elevation={6} ref={ref} variant="filled" {...props} />
)
);
并调用 Alert
组件,
<AlertFixed severity="error" sx={{ width: "50%" }}>
Failed
</AlertFixed>
这是工作 codesanbox。