我在 makeStyles
中使用 App.js
钩子为组件添加样式。目前,我在一个组件中使用了三个 makeStyles
钩子。这是否可以通过使用一个主钩来应用三个钩子的样式。我不确定我是否使用了最好的方法。如果有人可以帮助我,我将不胜感激。
App.js
const useStyles = makeStyles({
btn: {
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 45,
paddingRight: 45,
fontWeight: 600
},
gridMargin: {
margin: "auto"
},
topGrid: {
marginTop: "0.5rem",
},
marginRight: {
marginRight: "4rem"
}
})
const useTextFieldStyles = makeStyles({
root: {
fontWeight: "bold"
}
},{ name: "MuiInputBase" })
const useMuiFormLabel = makeStyles({
root: {
fontSize: "1.1rem",
color: "#B0B0B0",
top: "-13px",
'&$focused': {
color: "#B0B0B0",
fontSize: "1.1rem",
top: "-13px"
},
},
focused: {},
},{ name: "MuiFormLabel" })
const Login = (props) => {
const classes = useStyles();
const textFieldStyles = useTextFieldStyles();
const textFieldLabel = useMuiFormLabel();
return (
<Grid>
<Grid item xs={12} md={12}>
<TextField
className={textFieldStyles.root}
aria-label="username"
label="Username"
name="username"
type="text"
fullWidth
required
InputLabelProps={{ required: false, classes: { root: textFieldLabel.root, focused:textFieldLabel.focused } }}
/>
</Grid>
<Grid item xs={12} md={12}>
<TextField
label="Password"
aria-label="password"
type="password"
name="password"
color="primary"
fullWidth
required
className={textFieldStyles.root}
InputLabelProps={{ required: false, classes: { root: textFieldLabel.root, focused: textFieldLabel.focused } }}
/>
</Grid>
</Grid>
);
};
答案 0 :(得分:0)
由于 textField 组件由六个组件组成并且要覆盖特定组件的样式,我必须使用为 textField 中的组件提供的 props 来选择该组件,而不是将样式放在 textField 的 className 属性上 上面的代码可以重构为:-
const useStyles = makeStyles({
btn: {
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 45,
paddingRight: 45,
fontWeight: 600
},
gridMargin: {
margin: "auto"
},
topGrid: {
marginTop: "0.5rem",
},
marginRight: {
marginRight: "4rem"
},
textFieldWeight: {
fontWeight: "bold"
},
formLabelStyles: {
fontSize: "1.1rem",
color: "#B0B0B0",
top: "-13px",
'&$focused': {
color: "#B0B0B0",
fontSize: "1.1rem",
top: "-13px"
},
},
focused: {},
})
const Login = (props) => {
const classes = useStyles();
return (
<Grid>
<Grid item xs={12} md={12}>
<TextField
aria-label="username"
label="Username"
name="username"
type="text"
fullWidth
required
InputProps={{ classes: { root: classes.textFieldWeight } }}
InputLabelProps={{ required: false, classes: { root: classes.formLabelStyles, focused: classes.focused } }}
/>
</Grid>
<Grid item xs={12} md={12}>
<TextField
label="Password"
aria-label="password"
type="password"
name="password"
color="primary"
fullWidth
required
InputProps={{ classes: { root: classes.textFieldWeight } }}
InputLabelProps={{ required: false, classes: { root: classes.formLabelStyles, focused: classes.focused } }}
/>
</Grid>
</Grid>
);
}