防止Material-UI InputLabel移动到Select组件的左上角

Prevent Material-UI InputLabel from moving to the upper left of Select component

无论我尝试什么,我似乎都无法获得 Material-UI Select 组件的真正占位符功能。在 <Select /> 上使用占位符道具不起作用,看起来它要么没有将该道具传递给输入,要么没有以某种方式显示它。

通读 Material-UI 组件的 Select 演示代码,他们似乎通过使用 <InputLabel /> 实现了占位符功能。他们有一个厚脸皮的小动画,将它移动到输入的左上角。好的,很酷,这是一个不错的效果。但它不符合我们网站的设计,我想禁用它。不幸的是,disableAnimation 道具只会使标签跳到左上角,而不是完全消失。

我想要的是让我的下拉组件说 "Select Item" 作为占位符文本,然后当菜单打开时,该文本应该消失。如果用户在没有 select 任何东西的情况下点击下拉菜单,它只会 returns 。如果他们 select 一个值,该值应该替换占位符并且 "Select Item" 不应该出现在任何地方。

(注意:我在使用 react-select 时工作正常,但我需要使用 Material-UI 的连锁反应,所以我尝试覆盖他们的 MenuList和带有 Material UI 的 MenuItem 组件,但它将所有道具传递给 DOM 元素并抛出一堆错误。所以我回到绘图板并决定使用整个 Material UI Select 组件。)

当前代码:

const Dropdown = ({options, ...props}) => {
  const [selected, setSelected] = useState('');

  const testOptions = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

  const handleChange = (selected) => {
    setSelected(selected);
    console.log('is anything happening')
  }

  options = options || testOptions;

  const menuItems = options.map((option, index) => (
      <StyledMenuItem
        key={index}
        value={option.value}
        label={option.label}
      />
    ));

  return (
    <FormControl hiddenLabel>
      <InputLabel disableAnimation>Select Item</InputLabel>
      <StyledSelect
        value={selected}
        onChange={handleChange}

        variant="outlined"
        disableUnderline={true}
      >
        <MenuItem value="">
          <em>Select Item</em>
        </MenuItem>
        {menuItems}
      </StyledSelect>
    </FormControl>
  )
};


const StyledMenuItem = styled(MenuItem)`
  min-height: 32px;
  height: 32px;
  padding: 0 12px;
  font-family: 'Work Sans', sans-serif;
  font-weight: 400;
  font-size: 17px;
  line-height: 20px;
  color: ${colors.primary800};
  outline: none;

  &:hover {
    background-color: ${colors.primary100};
  }

  & .MuiTouchRipple-root {
    color: ${colors.primary050};
  }
`

const StyledSelect = styled(Select)`

  input::-webkit-contacts-auto-fill-button,
    input::-webkit-credentials-auto-fill-button {
        display: none !important;
}
    border: 1px solid ${colors.primary400};
    border-radius: 2px;
    height: 40px;
    box-shadow: none;
    outline: none;

  & .MuiSelect-icon {
    fill: ${colors.primary300};
    width: 36px;
    height: 36px;
    top: inherit;
  }
`

我找不到真正干净的方法,但以下方法似乎可以解决问题:

<InputLabel shrink={false}>
    {selected !== '' && 'Select item'}
</InputLabel>

添加 shrink={false} 确保标签在聚焦时不会向上移动。使用默认的 Material-UI 样式,选项将位于 InputLabel 之上,因此在 selecting 时您将看不到它。然后,当一个值被 selected 时,selected 变量将被设置并且文本将从标签中隐藏。

如果 select 项由于您的自定义样式而没有出现在 InputLabel 上,您可以使用 onFocusonBlur 跟踪焦点以在select 专注。