Setting text color, outline, and padding on Material-ui Autocomplete component

后端 未结 1 1656
别跟我提以往
别跟我提以往 2020-11-30 13:09

We\'d like to change the text color, outline, and padding on a Material-ui Autocomplete component.

The code looks like this:

              

        
相关标签:
1条回答
  • 2020-11-30 13:24

    Here is the approach you tried (which worked as far as styling, but broke the Autocomplete functionality):

    renderInput={params => (
        <TextField
           {...params}
           label=""
           InputProps={{
              className: classes.inputColor
           }}
           variant="outlined"
           fullWidth
        />
    )}
    

    The above approach causes problems because the Autocomplete component passes InputProps as part of the params passed to TextField so the InputProps passed explicitly will completely replace the InputProps in params.

    Instead, you should leverage the inputRoot CSS class for the Autocomplete component:

    <Autocomplete classes={{inputRoot: classes.inputRoot}} .../>
    

    Below is a working example that sets the text color and customizes the outline colors.

    import React from "react";
    import TextField from "@material-ui/core/TextField";
    import Autocomplete from "@material-ui/lab/Autocomplete";
    import { makeStyles } from "@material-ui/core/styles";
    
    const useStyles = makeStyles(theme => ({
      inputRoot: {
        color: "purple",
        "& .MuiOutlinedInput-notchedOutline": {
          borderColor: "green"
        },
        "&:hover .MuiOutlinedInput-notchedOutline": {
          borderColor: "red"
        },
        "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
          borderColor: "purple"
        }
      }
    }));
    
    export default function ComboBox() {
      const classes = useStyles();
      return (
        <Autocomplete
          id="combo-box-demo"
          classes={classes}
          options={top100Films}
          getOptionLabel={option => option.title}
          style={{ width: 300 }}
          renderInput={params => {
            return (
              <TextField
                {...params}
                label="Combo box"
                variant="outlined"
                fullWidth
              />
            );
          }}
        />
      );
    }
    
    const top100Films = [
      { title: "The Shawshank Redemption", year: 1994 },
      { title: "The Godfather", year: 1972 },
    // Plus a bunch more
    ];
    

    Related answer:

    • Change border color on Material-UI TextField
    0 讨论(0)
提交回复
热议问题