问题
We'd like to change the text color, outline, and padding on a Material-ui Autocomplete component.
The code looks like this:
<FormControlLabel
label="Please enter desired service:"
labelPlacement="start"
control={
<Autocomplete
id="services"
options={props.serviceTypes}
getOptionLabel={option => option.name}
className={classes.inputRoot}
style={{ width: 400, paddingLeft: 20 }}
renderInput={params => (
<TextField
{...params}
label=""
className={classes.inputRoot}
variant="outlined"
fullWidth
/>
)}
onChange={setService}
/>
}
/>
We are able to change the TextInput color via code like this
InputProps={{
className: classes.inputColor
}}
but applying a style this way impacts the AutoComplete functionality (it loses the autocomplete functionality and behaves like a normal TextField).
We've tried a number of style and className options to no avail.
Appreciate any advice.
回答1:
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
来源:https://stackoverflow.com/questions/58984406/setting-text-color-outline-and-padding-on-material-ui-autocomplete-component