gpt4 book ai didi

css - Material 用户界面 : Why does setting background color on Select component hides the InputLabel text and how could I avoid it happening?

转载 作者:行者123 更新时间:2023-12-04 01:11:37 24 4
gpt4 key购买 nike

基本上我只是想改变下拉元素的背景颜色,但我也想保留默认文本显示在那里。现在,如果我没有在 Select 组件上显式设置背景颜色,则在 InputLabel 中指定的文本显示得很好,但只要我添加 style={{backgroundColor: "rgb(232, 241, 250)"}}Select,此 InputLabel 文本消失。为什么会发生这种情况,可以采取什么措施来解决这个问题?

代码片段:

<FormControl required fullWidth={true} size="small">
<InputLabel htmlFor="name" style={{color: "#000"}}>Тема обращения</InputLabel>
<Select
variant="filled"
style={{backgroundColor: "rgb(232, 241, 250)"}}
value={props.selectedTheme?.id || ''}
onChange={(e) => handleChange(e)}>
{props.themes.map(t => (<MenuItem key={t.id} value={t.id}>{t.name}</MenuItem>))}
</Select>
</FormControl>

截图:

Screenshot with the issue

最佳答案

您应该在 FormControl 元素而不是 Select 元素上指定 variant。将它放在 Select 上时,InputLabel 元素没有获得适合“填充”变体的样式。

这是 "filled" style for InputLabel 的开头:

  /* Styles applied to the root element if `variant="filled"`. */
filled: {
// Chrome's autofill feature gives the input field a yellow background.
// Since the input field is behind the label in the HTML tree,
// the input field is drawn last and hides the label with an opaque background color.
// zIndex: 1 will raise the label above opaque background-colors of input.
zIndex: 1,

请注意注释,指出需要 z-index 才能将标签提升到不透明背景颜色之上(正如您在“选择”中设置的那样)。

这是一个演示 FormControl 上的 variant 的工作示例:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const useStyles = makeStyles((theme) => ({
formControl: {
margin: theme.spacing(1),
minWidth: 120
},
selectEmpty: {
marginTop: theme.spacing(2)
}
}));

export default function SimpleSelect() {
const classes = useStyles();
const [age, setAge] = React.useState("");

const handleChange = (event) => {
setAge(event.target.value);
};

return (
<div>
<FormControl
variant="filled"
size="small"
className={classes.formControl}
>
<InputLabel
style={{ color: "#000" }}
id="demo-simple-select-filled-label"
>
Age
</InputLabel>
<Select
style={{ backgroundColor: "rgb(232, 241, 250)" }}
labelId="demo-simple-select-filled-label"
id="demo-simple-select-filled"
value={age}
onChange={handleChange}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</div>
);
}

Edit Filled Select with background color

关于css - Material 用户界面 : Why does setting background color on Select component hides the InputLabel text and how could I avoid it happening?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64648586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com