简体   繁体   中英

Style Material UI textfield

I'm trying to style a material-ui textfield but I don't get it to work the way I want. I just want a plain simple white input field with standard MUI animations. I want the textfield to always have a white background and text to be black.

You find the code on Code Sandbox: https://codesandbox.io/s/material-demo-2coo8?fontsize=14&hidenavigation=1&theme=dark

Thanks in advance!

You can custom style the TextField font and background color with the following code:

const useStyles = makeStyles((theme) => ({
  root: {
    "& .MuiInputBase-root": {
      color: 'black' //or try theme.palette.primary.main
      backgroundColor: 'white' //It should be white by default
    }
  }
}));

Then simply add the 'root' class to your TextField. As info, the above syntax is called JSS. .MuiInputBase-root is a class applied to the input component, which is a subcomponent of the TextField. This article explores the TextField component with dev tools open, so you can understand how the subcomponents work and get styled by MUI.

One more piece of info about the JSS syntax. Notice the 'space' between the '&' and the '.'. This space is important and acts as part of the selector, informing that.MuiInputBase-root class is on a child component of the parent that receive 'root' class styling.

I would highly suggest you to use functional components since it is the future of React.

Below you can see your example as functional component with regular Material-UI styles.

import React from "react";
import Grid from "@material-ui/core/Grid";
import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles(theme => ({
  root: { backgroundColor: "white" },
  box: { backgroundColor: "white" },
  input: {
    root: { backgroundColor: "white", color: "black" }
  }
}));

export default function FunctionalDemo() {
  const classes = useStyles();
  return (
    <Grid
      container
      direction="row"
      justify="center"
      alignItems="center"
      className={classes.root}
    >
      <Grid item xs={12} md={6} className={classes.box}>
        <form noValidate>
          <TextField
            id="email"
            label="Type here"
            variant="filled"
            color="secondary"
            className={classes.input.root}
          />
        </form>
      </Grid>
    </Grid>
  );
}

Code sandbox: https://codesandbox.io/s/material-ui-plain-text-field-x2s48?fontsize=14&hidenavigation=1&theme=dark

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM