我想要改变 Material-UI 的 TextField
浮动标题的颜色。
根据文档,我将颜色对象作为 floatingLabelStyle
传递:
<TextField floatingLabelStyle={{color: somecolor }} />
但这适用于标签的两种状态 - 悬停在输入框上以及不聚焦时在输入框上,此时标签应该是灰色的。
我想我正在覆盖某种CSS过渡效果,但不知道如何使其起作用。有什么建议吗?
我想要改变 Material-UI 的 TextField
浮动标题的颜色。
根据文档,我将颜色对象作为 floatingLabelStyle
传递:
<TextField floatingLabelStyle={{color: somecolor }} />
但这适用于标签的两种状态 - 悬停在输入框上以及不聚焦时在输入框上,此时标签应该是灰色的。
我想我正在覆盖某种CSS过渡效果,但不知道如何使其起作用。有什么建议吗?
这就行了
InputLabelProps={{
style: { color: '#fff' },
}}
您应该设置InputLabel的样式:
const styles = {
floatingLabelFocusStyle: {
color: "somecolor"
}
}
<TextField
label="Test"
id="test"
InputLabelProps={{
className: classes.floatingLabelFocusStyle,
}}
/>
TextField
内部的 InputLabel
的颜色来实现。 TextField
提供了 InputLabelProps
属性,以帮助您操作标签的属性。如果您只想在标签缩小(浮动)时更改颜色,则可以参考 inputLabelClasses.shrink
类名。请见下面的示例:import TextField from "@mui/material/TextField";
import { inputLabelClasses } from "@mui/material/InputLabel";
<TextField
label="Outlined secondary"
InputLabelProps={{
sx: {
// set the color of the label when not shrinked
color: "red",
[`&.${inputLabelClasses.shrink}`]: {
// set the color of the label when shrinked (usually when the TextField is focused)
color: "orange"
}
}
}}
/>
overrides: {
MuiInputLabel: {
root: {
color: "rgba(255, 255, 255, 0.87)",
},
},
},
您应该使用floatingLabelFocusStyle:
const styles = {
floatingLabelFocusStyle: {
color: "somecolor"
}
}
<TextField floatingLabelFocusStyle={styles.floatingLabelFocusStyle} />
您可以使用
root: {
'& .MuiFormLabel-root.Mui-disabled': {
color: 'red',
},
},
<TextField
label={label}
disabled={true}
className={classes.root}
/>
对于使用v5 Material UI主题的用户:
MuiInputLabel: {
styleOverrides: {
root: {
color: "white",
},
shrink: {
color: "white",
}
}
}
这将为TextField中的InputLabel和浮动的InputLabel都设置样式。如果你只想改变浮动的InputLabel,那么移除根属性即可。
注意:你还需要为TextField
添加布尔型属性shrink并将其设为true。
如需了解更多CSS规则名称,请查看MUI文档。
有两种方法可以在焦点事件上更改标签颜色:
使用makeStyle函数:
沙盒链接:https://codesandbox.io/s/material-demo-xnz77
说明:为了更加抽象化,我使用了style.js,在其中使用了JSS创建了通过makestyle函数创建的类。然后我使用了Input属性:
InputLabelProps={{
classes: {
root: classes.inputLabel,
focused: "focused"
}
}}
从而创建了一个文本框,当它聚焦时改变标签颜色。
使用withStyles:
参考1:https://codesandbox.io/s/3vzr41zmjm
参考2:https://github.com/mui-org/material-ui/issues/13840
我没有使用参考中的完全相同的代码,但是我对其进行了一些修改以适应我的需求。
这是一个错误,请向他们报告。
解释
我刚刚查看了他们的源代码。最初标签颜色设置为hintColor
。
const styles = {
...
floatingLabel: {
color: hintColor,
pointerEvents: 'none',
},
...
}
当焦点在标签上时,标签的颜色从muiTheme
变为focusColor
if (state.isFocused) {
styles.floatingLabel.color = focusColor;
}
如果有任何值,则覆盖原值
<TextFieldLabel
style={Object.assign(styles.floatingLabel, this.props.floatingLabelStyle)}
...
>
所以你的属性总是被覆盖,因此你总是看到相同的颜色。
您可以使用
import {FormControl, Input, InputLabel} from "@material-ui/core";
<FormControl>
<InputLabel style={{ color: '#fff' }}>Votre Nom et Prénom</InputLabel>
<Input value={Nom} onChange={event => setNom(event.target.value)} />
</FormControl>