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

ipe*_*n67 3 reactjs material-ui styled-components

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

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

我想要的是我的下拉组件将“选择项目”作为占位符文本说出来,然后当菜单打开时,该文本应该消失。它仅在用户单击下拉列表而不选择任何内容时返回。如果他们选择一个值,该值应替换占位符,并且“选择项目”不应出现在任何地方。

(注意:我在使用 react-select 时工作正常,但我需要使用 Material-UI 的涟漪效应,所以我尝试用 Material UI 覆盖它们的 MenuList 和 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;
  }
`
Run Code Online (Sandbox Code Playgroud)

jag*_*ler 5

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

<InputLabel shrink={false}>
    {selected !== '' && 'Select item'}
</InputLabel>
Run Code Online (Sandbox Code Playgroud)

添加shrink={false}确保标签在聚焦时不会向上移动。使用默认的 Material-UI 样式,选项将位于 InputLabel 之上,因此您在选择时不会看到它。Then, when a value is selected the selectedvariable will be set and the text will hide from the label.

如果选择项由于您的自定义样式而没有出现在 InputLabel 上,您可以跟踪焦点onFocusonBlur在选择聚焦时隐藏标签内容。