【问题标题】:How to change material-ui Textfield label styles in react如何在反应中更改material-ui Textfield标签样式
【发布时间】:2020-06-29 08:08:04
【问题描述】:

我是 Material-UI 的新手,我无法弄清楚如何更改以灰色显示的标签的颜色。我想要它在black。谁能帮我解决这个问题?

这是代码:

import React from "react";
import ReactDOM from "react-dom";
import { TextField, Button, Grid } from "@material-ui/core";

class App extends React.Component {
  render() {
    return (
      <Grid container justify={"center"} alignItems={"center"} spacing={1}>
        <Grid item>
          <TextField
            id="outlined-name"
            label="Name"
            value={"Enter value"}
            onChange={() => console.log("I was changed")}
            margin="normal"
            variant="outlined"
          />
        </Grid>
        <Grid item>
          <Button variant="contained" color="primary">
            Submit
          </Button>
        </Grid>
      </Grid>
    );
  }
}

这里是代码:“https://codesandbox.io/s/fancy-morning-30owz

【问题讨论】:

    标签: javascript html css reactjs material-ui


    【解决方案1】:

    如果您使用浏览器中的选择工具,您会发现:

    使用的类名是MuiFormLabel-root

    <label class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-shrink MuiInputLabel-outlined MuiFormLabel-filled" data-shrink="true" for="outlined-name">Name</label>
    

    所以使用nesting selector 将样式设置为TextField 组件

    功能组件

    import { makeStyles } from "@material-ui/core/styles";
    const useStyles = makeStyles(theme => ({
      root: {
        "& .MuiFormLabel-root": {
          color: "red" // or black
        }
      }
    }));
    ...
    const classes = useStyles();
    

    经典组件

    import { withStyles, createStyles } from "@material-ui/core/styles";
    const styles = theme => createStyles({
      root: {
        "& .MuiFormLabel-root": {
          color: "red"
        }
      }
    });
    ...
    const { classes } = this.props;
    ...
    export default withStyles(styles)(App);
    

    用法

    <TextField
      className={classes.root}
      ...
    >
    </TextField>
    

    这样可以改变标签颜色,如下图所示(目前为红色)



    在线试用:

    【讨论】:

    • 我们不能在不创建功能组件的情况下直接给类 Component 吗?
    【解决方案2】:

    如果你想把你的样式放在一个单独的文件中,你可以这样写:

    .MuiTextField-root > label {
        background-color: $bg-color;
        color: $color;
    }
    
    .MuiTextField-root > .MuiFormLabel-root.Mui-focused {
        color: $color;
    }
    
    

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 2021-07-07
      • 2021-11-17
      • 2021-02-18
      • 2021-02-19
      • 2018-04-29
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多