如何键入 Material-UI ListItemButton ref?

How to type Material-UI ListItemButton ref?

我写了这段代码,但我对这段内容有错误。为什么会发生这种情况,我该如何解决?我用MaterialUI,ListButtonItem来自material。

const AccordionChildItem = ({ parentLabel, title, action }: { title: string; parentLabel: string ; action:string}) => {
    const ListItemRef = useRef<HTMLElement>()
    const clickItem = () => {...}
        
    return (
        <ListItemButton
            ref={ListItemRef}
            className='list-item-for-navbar'
            onClick={clickItem}
            sx={{ py: '4px', pl: 1, pr: 5, fontSize: 14, mb: 1,color:'#8A92A6' }}>
                {title}
        </ListItemButton>
    )
}

错误:

No overload matches this call.
  Overload 1 of 3, '(props: { href: string; } & ListItemButtonBaseProps & Omit<{ action?: Ref<ButtonBaseActions> | undefined; centerRipple?: boolean | undefined; ... 11 more ...; TouchRippleProps?: Partial<...> | undefined; }, "classes"> & CommonProps & Omit<...>): Element', gave the following error.
    Type 'MutableRefObject<HTMLElement | undefined>' is not assignable to type '((instance: HTMLAnchorElement | null) => void) | RefObject<HTMLAnchorElement> | null | undefined'.
      Type 'MutableRefObject<HTMLElement | undefined>' is not assignable to type 'RefObject<HTMLAnchorElement>'.
        Types of property 'current' are incompatible.
          Type 'HTMLElement | undefined' is not assignable to type 'HTMLAnchorElement | null'.
            Type 'undefined' is not assignable to type 'HTMLAnchorElement | null'.
  Overload 2 of 3, '(props: { component: ElementType<any>; } & ListItemButtonBaseProps & Omit<{ action?: Ref<ButtonBaseActions> | undefined; ... 12 more ...; TouchRippleProps?: Partial<...> | undefined; }, "classes"> & CommonProps & Omit<...>): Element', gave the following error.
    Property 'component' is missing in type '{ children: string; ref: MutableRefObject<HTMLElement | undefined>; className: string; onClick: () => void; sx: { py: string; pl: number; pr: number; fontSize: number; mb: number; color: "#8A92A6"; }; }' but required in type '{ component: ElementType<any>; }'.
  Overload 3 of 3, '(props: DefaultComponentProps<ExtendButtonBaseTypeMap<ListItemButtonTypeMap<{}, "div">>>): Element', gave the following error.
    Type 'MutableRefObject<HTMLElement | undefined>' is not assignable to type '((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
      Type 'MutableRefObject<HTMLElement | undefined>' is not assignable to type 'RefObject<HTMLDivElement>'.
        Types of property 'current' are incompatible.
          Type 'HTMLElement | undefined' is not assignable to type 'HTMLDivElement | null'.
            Type 'undefined' is not assignable to type 'HTMLDivElement | null'.ts(2769)

最终,ListItemButton 组件呈现 <div> 元素。您需要将类型 HTMLDivElement 传递给 useRef 的泛型。

const ListItemRef = useRef<HTMLDivElement>()

终于对我有用了

const ListItemRef = useRef<HTMLDivElement|null>(null)