首页 > 解决方案 > MUI - Outlined select label is not rendering properly

问题描述

As per the demo, the label for a MUI outlined select input should sit on top of the top border of the select box.

enter image description here

However, in my application, the z-index of the label seems to be placing it behind the top border and thus it looks like a line is cutting through the label.

enter image description here

I have pretty much taken the code exactly from the documentation, and as far as I know, do not have any styles conflicting with this input element. I have compared the styles in the debugger to what I have and what is present in the documentation, and I do not see any of my first party CSS files causing a different style to be set on the element.

Any idea what might be going wrong here?

Here is the source code:

<FormControl variant='outlined' style={{ width: '100%' }} margin={'1'}>
  <InputLabel id='test-select-label'>Label</InputLabel>
  <Select
    labelId='test-select-label'
    id='test-select'
    value={'test1'}
    onChange={e => setTest(e.target.value)}
    size='small'
  >
    <MenuItem key={1} value={'test'} >Test 1</MenuItem>
    <MenuItem key={2} value={'test2'} >Test 2</MenuItem>
  </Select>
</FormControl>

标签: cssreactjsdrop-down-menumaterial-ui

解决方案


解决方案 1:使用TextField

这是TextField为了什么。它在内部使用 FormControlandInputLabel并确保它们可以很好地协同工作。您可以通过覆盖道具来告诉TextField渲染:selectinputselect

<TextField
  value={value}
  onChange={(e) => setValue(e.target.value)}
  select // tell TextField to render select
  label="Label"
>
  <MenuItem key={1} value="test">
    Test 1
  </MenuItem>
  <MenuItem key={2} value="test2">
    Test 2
  </MenuItem>
</TextField>

有关如何TextField工作的更多详细信息,请参阅答案。

解决方案 2:使用Select

如果您决定使用Select,则需要编写更多代码来完成相同数量的工作:

将标签文本作为InputLabel子项传递

<InputLabel id="test-select-label">Label</InputLabel>

Select当放置在组件内部FormControl和组件旁边时,此标签文本将作为标签呈现在屏幕上Select

将标签文本传递给组件的labelpropsSelect

该标签文本是隐藏的,用于在标签收缩border-top时覆盖和移除实际标签所占据的部分。Select

<Select labelId="test-select-label" label="Label">

把它放在一起,我们会得到类似下面的东西,请注意,使用这种方法,我们需要将标签设置在 2 个不太干燥的不同位置,所以我更喜欢第一种方法。

<FormControl>
  <InputLabel id="test-select-label">Label</InputLabel>
  <Select
    value={value}
    onChange={(e) => setValue(e.target.value)}
    labelId="test-select-label"
    label="Label"
  >
    <MenuItem key={1} value="test">
      Test 1
    </MenuItem>
    <MenuItem key={2} value="test2">
      Test 2
    </MenuItem>
  </Select>
</FormControl>

现场演示

Codesandbox 演示


推荐阅读