使Material-UI InputAdornment图标仅在选中时可见?

时间:2019-08-12 02:23:11

标签: reactjs material-ui

是否可以仅在用户选择文本字段时使此沙箱(https://codesandbox.io/s/material-demo-w385h)中的Material-UI图标装饰可见?

代码:

<TextField
  className={classes.margin}
  id="input-with-icon-textfield"
  label="TextField"
  InputProps={{
    startAdornment: (
      <InputAdornment position="start">
        <AccountCircle />
      </InputAdornment>
    )
  }}
/>

我希望找到一个使用Material-UI道具的干净解决方案。

1 个答案:

答案 0 :(得分:0)

我在发布此消息后立即意识到了解决方案:

https://codesandbox.io/s/material-demo-w385h

设置IconAdornment时包含InputProps的变量isSelected === true

OnFocussetIsSelected(true)OnBlursetIsSelected(false)

  const [isSelected, setIsSelected] = useState(false);

  const iconAdornment = isSelected
    ? {
        startAdornment: (
          <InputAdornment position="start">
            <AccountCircle />
          </InputAdornment>
        )
      }
    : {};

  return (
    <TextField
      className={classes.margin}
      id="input-with-icon-textfield"
      label="TextField"
      InputProps={iconAdornment}
      onFocus={e => setIsSelected(true)}
      onBlur={e => setIsSelected(false)}
    />
  );