更改 Material-UI TextField 上的边框颜色
IT技术
reactjs
material-ui
2021-03-24 02:25:31
1个回答
以下是如何覆盖TextField
. 这显示使用三种不同的颜色:一种用于默认(绿色),一种用于悬停(红色),另一种用于输入具有焦点时(紫色)。
import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles({
root: {
"& .MuiOutlinedInput-root .MuiOutlinedInput-notchedOutline": {
borderColor: "green"
},
"&:hover .MuiOutlinedInput-root .MuiOutlinedInput-notchedOutline": {
borderColor: "red"
},
"& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: "purple"
},
"& .MuiOutlinedInput-input": {
color: "green"
},
"&:hover .MuiOutlinedInput-input": {
color: "red"
},
"& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-input": {
color: "purple"
},
"& .MuiInputLabel-outlined": {
color: "green"
},
"&:hover .MuiInputLabel-outlined": {
color: "red"
},
"& .MuiInputLabel-outlined.Mui-focused": {
color: "purple"
}
}
});
function App() {
const classes = useStyles();
return (
<div className="App">
<TextField
className={classes.root}
defaultValue="My Default Value"
variant="outlined"
label="My Label"
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
下面是使用 MUI v5 的类似示例。这使用styled
代替makeStyles
并利用更类型安全的方式(在 v5 中添加)来引用全局类名(例如.${outlinedInputClasses.root}
),但继续对全局类名(例如)进行硬编码.MuiOutlinedInput-root
仍然可以正常工作(当硬编码,但对错别字的保护较少,并且没有自动完成帮助)。
import React from "react";
import ReactDOM from "react-dom";
import TextField from "@mui/material/TextField";
import { outlinedInputClasses } from "@mui/material/OutlinedInput";
import { inputLabelClasses } from "@mui/material/InputLabel";
import { styled } from "@mui/material/styles";
const StyledTextField = styled(TextField)({
[`& .${outlinedInputClasses.root} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: "green"
},
[`&:hover .${outlinedInputClasses.root} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: "red"
},
[`& .${outlinedInputClasses.root}.${outlinedInputClasses.focused} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: "purple"
},
[`& .${outlinedInputClasses.input}`]: {
color: "green"
},
[`&:hover .${outlinedInputClasses.input}`]: {
color: "red"
},
[`& .${outlinedInputClasses.root}.${outlinedInputClasses.focused} .${outlinedInputClasses.input}`]: {
color: "purple"
},
[`& .${inputLabelClasses.outlined}`]: {
color: "green"
},
[`&:hover .${inputLabelClasses.outlined}`]: {
color: "red"
},
[`& .${inputLabelClasses.outlined}.${inputLabelClasses.focused}`]: {
color: "purple"
}
});
function App() {
return (
<div className="App">
<StyledTextField
defaultValue="My Default Value"
variant="outlined"
label="My Label"
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
相关回答:
其它你可能感兴趣的问题