Next.js Material UI useAutoComplete -警告:一个包含“key”prop的props对象正在扩展到JSX中

hgb9j2n6  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(340)

我正在尝试使用mui doc中给出的现有代码(自定义钩子):

<Root>
  <div {...getRootProps()}>
    <Label {...getInputLabelProps()}>Tags</Label>
    <InputWrapper
      ref={setAnchorEl}
      className={focused ? "focused" : ""}
    >
      {value.map((tag: string, index: number) => (
        <StyledTag key={tag} label={tag} {...getTagProps({ index })} />
      ))}
      <input {...getInputProps()} />
    </InputWrapper>
  </div>
  {groupedOptions.length > 0 ? (
    <Listbox {...getListboxProps()}>
      {(groupedOptions as typeof tags).map((option, index) => (
        <li key={index} {...getOptionProps({ option, index })}>
          <span>{option}</span>
          <CheckIcon fontSize="small" />
        </li>
      ))}
    </Listbox>
  ) : null}
</Root>

首先,我得到了丢失关键 prop 的警告。将key={index}插入到<li>中后,如下所示:<li key={index} {...getOptionProps({ option, index })}>。点击输入搜索栏后,我收到以下新警告:

如何解决这个问题?

wxclj1h5

wxclj1h51#

谢谢你的帮助,这是解决方案。
问题在于nextjs如何呈现其组件。长话短说,这是由于在自动完成组件中对从迭代创建的元素设置不正确的key。虽然这很乏味,但您必须明确地声明所有元素(包括所有子元素)的UNIQUE键。
这个问题是我在这个Post中解决的问题的一个小小的变化。唯一的区别是,这一次迭代的元素有嵌套的元素。
比如说

// This has nested elements
      {(groupedOptions as typeof top100Films).map((option, index) => (
        <li {...getOptionProps({ option, index })} key={index}>
          <span key={index + 1000}>{option.title}</span>
          <CheckIcon fontSize="small" key={index + 2000} />
        </li>
      ))}

虽然它没有嵌套元素,

{(groupedOptions as typeof top100Films).map((option, index) => (
        <li {...getOptionProps({ option, index })} key={index}>
            {option.title}
        </li>
      ))}

如果您没有嵌套元素,我前面的解决方案就足够了,您只将键设置到顶部元素。就像我说的,所有元素都应该有键,所有键都应该是唯一的。所以注意到我是如何通过添加1000或2000来创建一个“伪”唯一密钥的?您应该实现一个逻辑来生成唯一键,因此仅仅使用索引是不够的,因为子元素需要一种方法来获取唯一键。
此外,您应该始终将key={index}放在跨页(如{...getOptionProps({ option, index })})之后,以便它看起来像<li {...getOptionProps({ option, index })} key={index}>。这样,新设置的关键点将覆盖由跨页设置的关键点。

    • TLDR**:所以要解决你的问题

1.正确放置钥匙(特别是在展开后)
1.将键放置到迭代中的所有元素(如子元素)
这里是你的问题的完整代码。关注我所做的修改和评论。复制粘贴到您的本地机器上并运行它,它的工作。如果你还有什么问题,请告诉我。

'use client'

import * as React from 'react'
import useAutocomplete, {
  AutocompleteGetTagProps,
} from '@mui/base/useAutocomplete'
import CheckIcon from '@mui/icons-material/Check'
import CloseIcon from '@mui/icons-material/Close'
import { styled } from '@mui/material/styles'
import { autocompleteClasses } from '@mui/material/Autocomplete'

const Root = styled('div')(
  ({ theme }) => `
  color: ${
    theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.65)' : 'rgba(0,0,0,.85)'
  };
  font-size: 14px;
`
)

const Label = styled('label')`
  padding: 0 0 4px;
  line-height: 1.5;
  display: block;
`

const InputWrapper = styled('div')(
  ({ theme }) => `
  width: 300px;
  border: 1px solid ${theme.palette.mode === 'dark' ? '#434343' : '#d9d9d9'};
  background-color: ${theme.palette.mode === 'dark' ? '#141414' : '#fff'};
  border-radius: 4px;
  padding: 1px;
  display: flex;
  flex-wrap: wrap;

  &:hover {
    border-color: ${theme.palette.mode === 'dark' ? '#177ddc' : '#40a9ff'};
  }

  &.focused {
    border-color: ${theme.palette.mode === 'dark' ? '#177ddc' : '#40a9ff'};
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  & input {
    background-color: ${theme.palette.mode === 'dark' ? '#141414' : '#fff'};
    color: ${
      theme.palette.mode === 'dark'
        ? 'rgba(255,255,255,0.65)'
        : 'rgba(0,0,0,.85)'
    };
    height: 30px;
    box-sizing: border-box;
    padding: 4px 6px;
    width: 0;
    min-width: 30px;
    flex-grow: 1;
    border: 0;
    margin: 0;
    outline: 0;
  }
`
)

interface TagProps extends ReturnType<AutocompleteGetTagProps> {
  index: number // Get index to implement a unique key
  label: string
}

function Tag(props: TagProps) {
  const { label, onDelete, index, ...other } = props // Get index to implement a unique key
  return (
    // Place unique key to all elements
    <div {...other} key={index}>
      <span key={props.key + 3000}>{label}</span>
      <CloseIcon onClick={onDelete} key={index + 1000} />
    </div>
  )
}

const StyledTag = styled(Tag)<TagProps>(
  ({ theme }) => `
  display: flex;
  align-items: center;
  height: 24px;
  margin: 2px;
  line-height: 22px;
  background-color: ${
    theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.08)' : '#fafafa'
  };
  border: 1px solid ${theme.palette.mode === 'dark' ? '#303030' : '#e8e8e8'};
  border-radius: 2px;
  box-sizing: content-box;
  padding: 0 4px 0 10px;
  outline: 0;
  overflow: hidden;

  &:focus {
    border-color: ${theme.palette.mode === 'dark' ? '#177ddc' : '#40a9ff'};
    background-color: ${theme.palette.mode === 'dark' ? '#003b57' : '#e6f7ff'};
  }

  & span {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  & svg {
    font-size: 12px;
    cursor: pointer;
    padding: 4px;
  }
`
)

const Listbox = styled('ul')(
  ({ theme }) => `
  width: 300px;
  margin: 2px 0 0;
  padding: 0;
  position: absolute;
  list-style: none;
  background-color: ${theme.palette.mode === 'dark' ? '#141414' : '#fff'};
  overflow: auto;
  max-height: 250px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1;

  & li {
    padding: 5px 12px;
    display: flex;

    & span {
      flex-grow: 1;
    }

    & svg {
      color: transparent;
    }
  }

  & li[aria-selected='true'] {
    background-color: ${theme.palette.mode === 'dark' ? '#2b2b2b' : '#fafafa'};
    font-weight: 600;

    & svg {
      color: #1890ff;
    }
  }

  & li.${autocompleteClasses.focused} {
    background-color: ${theme.palette.mode === 'dark' ? '#003b57' : '#e6f7ff'};
    cursor: pointer;

    & svg {
      color: currentColor;
    }
  }
`
)

export default function CustomizedHook() {
  const {
    getRootProps,
    getInputLabelProps,
    getInputProps,
    getTagProps,
    getListboxProps,
    getOptionProps,
    groupedOptions,
    value,
    focused,
    setAnchorEl,
  } = useAutocomplete({
    id: 'customized-hook-demo',
    defaultValue: [top100Films[1]],
    multiple: true,
    options: top100Films,
    getOptionLabel: (option) => option.title,
  })

  return (
    <Root>
      <div {...getRootProps()}>
        <Label {...getInputLabelProps()}>Customized hook</Label>
        <InputWrapper ref={setAnchorEl} className={focused ? 'focused' : ''}>
          {value.map((option: FilmOptionType, index: number) => (
            // Place unique key to all elements
            <StyledTag
              label={option.title}
              {...getTagProps({ index })}
              key={index}
              index={index}
            />
          ))}
          <input {...getInputProps()} />
        </InputWrapper>
      </div>
      {groupedOptions.length > 0 ? (
        <Listbox {...getListboxProps()}>
          {(groupedOptions as typeof top100Films).map((option, index) => (
            // Place unique key to all elements
            <li {...getOptionProps({ option, index })} key={index}>
              <span key={index + 1000}>{option.title}</span>
              <CheckIcon fontSize="small" key={index + 2000} />
            </li>
          ))}
        </Listbox>
      ) : null}
    </Root>
  )
}

interface FilmOptionType {
  title: string
  year: number
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: 'The Shawshank Redemption', year: 1994 },
  { title: 'The Godfather', year: 1972 },
  { title: 'The Godfather: Part II', year: 1974 },
  // ...
]

相关问题