【问题标题】:Building a custom component with MenuItem of Material UI使用 Material UI 的 MenuItem 构建自定义组件
【发布时间】: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


    【解决方案1】:

    改用innerRef

    <MenuItem innerRef={ref} {...props}></MenuItem>
    

    【讨论】:

    • 编译错误消失了,但现在我留下了与 相同的错误,即:
    • 组件中发生错误:在 ButtonBase 的 li (localhost:3000/static/js/0.chunk.js:15025:22) And Uncaught TypeError: Cannot add property current, object is not extensible
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签