简体   繁体   English

React MUI - 清除自动完成组件上的输入

[英]React MUI - Clearing input on Autocomplete component

I have an Autocomplete component which displays the coutries name and flags as in the example from the MUI doc.我有一个自动完成组件,它显示国家名称和标志,如 MUI 文档中的示例所示。

编辑 CountrySelect 材质演示(分叉)

My goal is simply the following: once the Autocomplete component is clicked, the country's name must be cleared displaying only the placeholder.我的目标很简单:单击自动完成组件后,必须清除国家名称,仅显示占位符。

I achieved this with a simple onClick event in the renderInput which triggers the following function:我通过 renderInput 中的一个简单的onClick事件实现了这一点,该事件触发了以下函数:

  const handleClear = (e) => {
    e.target.value = "";
  };

If trying the code everything works as expected, apparently .如果尝试代码一切都按预期工作,显然 Actually, the clearing happens only when the country's name is clicked, but if a different portion of the component is clicked, like the flag or the dropdown arrow , the country's name is simply focused, not cleared .实际上,在单击国家名称时才会清除,但如果单击组件的不同部分,例如标志下拉箭头则国家名称只是聚焦,而不是清除

In short, here the current behaviour:简而言之,这里是当前的行为:

当前行为

and here the expected behaviour:这里是预期的行为: 预期的

Is there a way to fix this?有没有办法来解决这个问题?

That's behavior occurs because when you click on the flag, the e.target won´t be the input element, but the wrapper div .出现这种行为是因为当您单击标志时, e.target将不是input元素,而是包装器div You can see this just adding a console.log to the handleClear function:您只需将console.log添加到handleClear函数即可看到:

const handleClear = (e) => {
    console.log("clicked TARGET ELEMENT: ", e.target);

    // If you click on the input, will see:
    // <input ...

    // And if you click on the flag, you will see:
    // <div ...
};

If you want to control the input state value and the text value separately, you probably should go with the two states control - check it on MUI docs .如果您想分别控制输入状态值和文本值,您可能应该使用两种状态控制 - 在 MUI 文档中检查它。

The code will be something like:代码将类似于:

export default function CountrySelect() {
  const [value, setValue] = useState(null);
  const [inputValue, setInputValue] = React.useState("");

  const handleClear = (e) => {
    console.log("clicked TARGET ELEMENT: ", e.target);
    setInputValue("");
  };

  return (
    <Autocomplete
      id="country-select-demo"
      disableClearable
      value={value}
      onChange={(event, newValue) => {
        setValue(newValue);
      }}
      inputValue={inputValue}
      onInputChange={(event, newInputValue) => {
        setInputValue(newInputValue);
      }}
      openOnFocus
      sx={{ width: 300 }}
      options={countries}
      autoHighlight
      getOptionLabel={(option) => option.label}
      renderOption={(props, option) => (
        <Box
          component="li"
          sx={{ "& > img": { mr: 2, flexShrink: 0 } }}
          {...props}
        >
          <img
            loading="lazy"
            width="20"
            src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
            srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
            alt=""
          />
          {option.label} ({option.code}) +{option.phone}
        </Box>
      )}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Choose a country"
          placeholder="Choose a country"
          onClick={handleClear}
          InputProps={{
            ...params.InputProps,
            startAdornment: value ? (
              <InputAdornment disablePointerEvents position="start">
                <img
                  loading="lazy"
                  width="48"
                  src={`https://flagcdn.com/w20/${value.code.toLowerCase()}.png`}
                  srcSet={`https://flagcdn.com/w40/${value.code.toLowerCase()}.png 2x`}
                  alt=""
                />
              </InputAdornment>
            ) : null
          }}
        />
      )}
    />
  );
}

Instead of using onClick on TextField, you can use onOpen props and pass handleClear function in it.您可以使用onOpen道具并在其中传递handleClear函数,而不是在 TextField 上使用onClick It works then.然后就可以了。 Selected value gets cleared whenever autocomplete is open.每当自动完成打开时,选定的值就会被清除。

Working Demo: CodeSandBox.io工作演示: CodeSandBox.io

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM