【发布时间】:2021-07-16 21:26:11
【问题描述】:
我们正在使用对 typescript 的反应。
我目前正在包装大多数 MUI 组件以提高灵活性。 我们实际上遇到了 MenuItem 的问题,出现的第一个错误是: “函数组件不能被赋予 refs。尝试访问这个 ref 将会失败。你的意思是使用 React.forwardRef() 吗?”.
我的组件是 Function 组件,所以我确实切换到了 ForwardRefRenderFunction。但是,我无法让它工作。
这是我的渲染函数:
interface IDMSMenuItemProps extends MenuItemProps<"li", { button?: true }> {}
const DMSMenuItem: React.ForwardRefRenderFunction<HTMLButtonElement, IDMSMenuItemProps> = (props, ref) => {
return (
<MenuItem ref={ref} {...props}></MenuItem>
);
};
export default DMSMenuItem;
这个渲染函数导致编译错误:
No overload matches this call.
The last overload gave the following error.
Type '((instance: HTMLButtonElement | null) => void) | MutableRefObject<HTMLButtonElement | null> | null' is not assignable to type '((instance: HTMLLIElement | null) => void) | RefObject<HTMLLIElement> | null | undefined'.
Type '(instance: HTMLButtonElement | null) => void' is not assignable to type '((instance: HTMLLIElement | null) => void) | RefObject<HTMLLIElement> | null | undefined'.
Type '(instance: HTMLButtonElement | null) => void' is not assignable to type '(instance: HTMLLIElement | null) => void'.
如果我使用 React.ForwardRefRenderFunction
The above error occurred in the <li> component:
at li
at ButtonBase (https://localhost:3000/static/js/0.chunk.js:15025:22)
at WithStyles(ForwardRef(ButtonBase)) (https://localhost:3000/static/js/0.chunk.js:197724:31)
Uncaught TypeError: Cannot add property current, object is not extensible
at setRef (:3000/static/js/0.chunk.js:48576)
at :3000/static/js/0.chunk.js:48759
父组件是这样的:
interface IDMSSelectProps extends SelectProps {
hint?: string;
}
const DMSSelect: React.FunctionComponent<IDMSSelectProps> = (props) => {
return (
<FormControl error={props.error} fullWidth={true}>
<InputLabel>{props.label}</InputLabel>
<Select fullWidth={true} {...props}>
{props.children}
</Select>
<FormHelperText>{props.hint}</FormHelperText>
</FormControl>
);
};
export default DMSSelect;
用例是:
<DMSSelect defaultValue="" hint="DMS TEST" label="DMS Selecto">
<DMSMenuItem value="">Empty Value for First Option</DMSMenuItem>
</DMSSelect>
如何使用 menuitem 实现自定义组件?
编辑:即使使用渲染功能仍然存在前向引用错误:
Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `ForwardRef(Menu)`.
at DMSMenoItem
at ul
【问题讨论】:
标签: reactjs material-ui