函数组件不能给出引用。 MUI v5 自动完成

问题描述 投票:0回答:1

我正在尝试在 Autocomplete MUI v5 中使用 ListboxComponent 属性的自定义组件,但我收到此错误:

函数组件不能被赋予引用。尝试访问此引用将失败。您的意思是使用 React.forwardRef() 吗?

自动完成组件:

    <Autocomplete
    // other props...
    ListboxComponent={p => {
          // p is a type HTMLAttributes<HTMLElement>

          const props = {
            ...p,
            test: 'test'
          }
          return <ListBox {...props} />
        }}
    <Autocomplete/>

ListBox组件:

'use client'
import { Children, cloneElement, forwardRef } from 'react'
import { useAutocompleteContext } from '../../context/AutocompleteContext'
import type { HTMLAttributes, ReactElement, Ref } from 'react'
import * as S from './styled'

const ListBoxComponent = (props: HTMLAttributes<HTMLElement>, ref: Ref<HTMLElement>) => {
  const { children, ...rest } = props
  const { totalRecords, options, loading, handleNextFetch } = useAutocompleteContext()

  const hasMore = options.length < totalRecords

  return (
    <S.InfiniteScrollComponent
      next={() => handleNextFetch()}
      hasMore={hasMore}
      dataLength={options.length}
      isLoading={loading}
      loadingIcon="table"
      maxHeight={80}>
      {Children.map(children, (child, index) =>
        cloneElement(child as ReactElement, { ...rest, key: `option-${index}` })
      )}
    </S.InfiniteScrollComponent>
  )
}

export const ListBox = forwardRef<HTMLElement, HTMLAttributes<HTMLElement>>(
  ListBoxComponent
)

如果使用此变体,它将在没有警告的情况下工作,但我想转发我自己的道具,以免使用 Context

<Autocomplete
   // other props...
   ListboxComponent={ListBox}
<Autocomplete/>

在这两种方法中,它都能根据需要正常工作

reactjs next.js material-ui autocomplete ref
1个回答
0
投票

看起来您没有在自定义组件中使用 ref :

 <S.InfiniteScrollComponent

      // here we pass ref prop
      ref={ref}

      next={() => handleNextFetch()}
      hasMore={hasMore}
      dataLength={options.length}
      isLoading={loading}
      loadingIcon="table"
      maxHeight={80}>
      {Children.map(children, (child, index) =>
        cloneElement(child as ReactElement, { ...rest, key: `option-${index}` })
      )}
    </S.InfiniteScrollComponent>

另外,请确保您使用实际包装的

ListBox
但未包装的
ListBoxComponent
。这可能是您的错误消息的实际原因。

© www.soinside.com 2019 - 2024. All rights reserved.