css - 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.
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.
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>
解决方案
解决方案 1:使用TextField
这是TextField
为了什么。它在内部使用 FormControl
andInputLabel
并确保它们可以很好地协同工作。您可以通过覆盖道具来告诉TextField
渲染:select
input
select
<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
。
将标签文本传递给组件的label
propsSelect
该标签文本是隐藏的,用于在标签收缩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>
现场演示
推荐阅读
- javascript - discord.js 检查没有叶子的用户邀请
- asp.net - 配置错误(执行此操作时出错)
- reactjs - 如何使用 react-routing 按 ID 返回页面?
- google-app-engine - 使用 App Engine (API) 和 Cloud Storage Bucket(前端)在 GCP 上托管 Node.js
- strapi - Strapi 如何在 CRON 中查询关系
- javascript - 我在 javascript 中生成哈希字符串时遇到问题
- sql - 按 SQL 中的第一个值对行序列进行分组
- swift - 闭包功能无法正常工作
- php - 通过自定义标头变化的 Http 缓存
- amazon-web-services - AWS > Lambda > Canary 函数