关于reactjs:防止Material-UI InputLabel移至Select组件的左上方

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

无论我如何尝试,我似乎都无法为Material-UI Select组件获得真正的占位符功能。在<Select />上使用占位符prop无效,并且看起来好像没有将该prop传递给输入,还是没有以某种方式显示它。

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

我想让我的下拉组件说"选择项目"作为占位符文本,然后在打开菜单时,该文本应消失。仅当用户单击下拉菜单但未选择任何内容时,它才会返回。如果他们选择一个值,则该值应替换占位符,并且" Select Item "不应出现在任何地方。

(注意:我在使用react-select时可以正常工作,但是我需要使用Material-UI的波纹效果,因此我尝试使用Material UI覆盖它们的MenuList和MenuItem组件,但是通过了所有道具都归因于DOM元素,并引发了一系列错误。因此,我回到了绘图板上,决定使用整个Material UI Select组件。)

当前代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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="">
          Select Item
        </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;
  }
`


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

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

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

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