因此,我将 Material UI Autocomplete 组件与 Next.js 一起使用,并收到此警告,我尝试解决但无法解决。错误来自 renderInput 函数吗?如果是这样,“...params”中没有“key”属性,所以我无法像警告消息建议的那样删除。
我该如何解决这个问题?
const top100Films = ['a', 'b', 'c', 'd'];
// props.tags = ['a', 'c']
<Autocomplete
multiple
id="tags-outlined"
onChange={(event: any, newValue: string[]) => {
props.onTagsChange(newValue);
}}
options={top100Films}
value={props.tags}
filterSelectedOptions
renderInput={(params) => (
<TextField
{...params}
label="Tags"
placeholder="Tag"
/>
)}
/>
Run Code Online (Sandbox Code Playgroud)
hydration-error-info.js?32aa:26 Warning: A props object containing a "key" prop is being spread into JSX:
let props = {key: someKey, tabIndex: ..., role: ..., id: ..., onMouseOver: ..., onClick: ..., onTouchStart: ..., data-option-index: ..., aria-disabled: ..., aria-selected: ..., className: ..., children: ...};
<li {...props} />
React keys must be passed directly to JSX without using spread:
let props = {tabIndex: ..., role: ..., id: ..., onMouseOver: ..., onClick: ..., onTouchStart: ..., data-option-index: ..., aria-disabled: ..., aria-selected: ..., className: ..., children: ...};
<li key={someKey} {...props} />
Run Code Online (Sandbox Code Playgroud)
min*_*aej 26
该问题是由于 nextjs 渲染其组件的方式造成的。具体来说,是由于组件key中的选项列表和标签设置不当造成的Autocomplete。虽然这很乏味,但您必须使用下面的方法明确声明标签和选项的键。
您可以使用renderOption并renderTags提供 byAutocomplete来解决此问题。
renderOption={(props, option) => {
return (
<li {...props} key={option}>
{option.label}
</li>
);
}}
Run Code Online (Sandbox Code Playgroud)
和
renderTags={(tagValue, getTagProps) => {
return tagValue.map((option, index) => (
<Chip {...getTagProps({ index })} key={option} label={option} />
))
}}
Run Code Online (Sandbox Code Playgroud)
所以......在你的情况下它将变成:
<Autocomplete
multiple
id="tags-outlined"
options={top100Films}
onChange={(event: any, newValue: string[]) => {
props.onTagsChange(newValue);
}}
value={props.tags}
filterSelectedOptions
renderOption={(props, option) => {
return (
<li {...props} key={option}>
{option}
</li>
)
}}
renderTags={(tagValue, getTagProps) => {
return tagValue.map((option, index) => (
<Chip {...getTagProps({ index })} key={option} label={option} />
))
}}
renderInput={(params) => (
<TextField
{...params}
label="Tags"
placeholder="Tag"
/>
)}
/>
Run Code Online (Sandbox Code Playgroud)
您可以在此处renderOption阅读有关和 的更多信息。renderTags
附言。不要忘记Chip从 Mui 导入!
| 归档时间: |
|
| 查看次数: |
7629 次 |
| 最近记录: |