Ger*_*mon 9 autocomplete reactjs material-ui
将空字符串传递给 Autocomplete 时,它会抛出一个控制台警告,指出该值无效。
我怎样才能让这个警告消失?它不会导致任何问题,但是每次重新渲染时都将其抛出到控制台中非常烦人。我似乎让它不发生的唯一方法是将字段的初始值设置为空,在我的理解中,这不是我应该作为输入的默认值的内容。
当将空字符串的默认值传递给自动完成组件时,它会抛出一个控制台警告,指出该值空字符串无效。
如果给 Autocomplete 的值是空字符串,则不应抛出警告或错误。
这是一个展示错误的链接:https : //codesandbox.io/s/material-demo-n0ijt
1) 将空字符串传递给 Autocomplete 组件的 value 属性。
您可以将其null
用作初始状态,这可能会实现您的尝试
value={data.value || null}
如果你将它设置为 undefined 它会抱怨受控组件,这样即使在我使用自动完成之后我也不会收到错误
小智 7
我解决了它处理输入字符串为空的情况(你没有这样做)。您的沙箱中需要 3 样东西:
getOptionSelected
,当值为空字符串时必须返回 true;这样 React 选择一个选项,警告消失。getOptionLabel
,处理空字符串的情况。我会做以下事情:getOptionLabel={option => option.title ? option.title : ''}
Run Code Online (Sandbox Code Playgroud)
因此,如果选项有标题,则返回标题,否则返回可视化的空字符串。
onChange
处理空字符串,这样onChange={(e, selectedObject) => {
if (selectedObject !== null)
setValue(selectedObject)
}}
Run Code Online (Sandbox Code Playgroud)
总体:
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
export default function FreeSoloCreateOption() {
const [value, setValue] = React.useState("");
return (
<Autocomplete
value={value}
id="empty-string-demo"
options={top100Films}
getOptionLabel={option => option.title ? option.title : ''}
getOptionSelected={(option, value) => {
//nothing that is put in here will cause the warning to go away
if (value === "") {
return true;
} else if (value === option) {
return true;
}
}}
onChange={(e, selectedObject) => {
if (selectedObject !== null)
setValue(selectedObject)
}}
renderOption={option => option.title}
style={{ width: 300 }}
renderInput={params => (
<TextField
{...params}
label="Default Value of Empty String"
variant="outlined"
/>
)}
/>
);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6469 次 |
最近记录: |