如何在 Material-ui 自动完成中设置单个元素的样式

How to style a single element inside Material-ui autocomplete

我在 Material-UI 自动完成中有一个电影数组,我想将我最喜欢的电影 - 办公室 Space- 添加到这个数组。有什么方法可以为这部电影自定义样式,使其具有文本 color: primary?

export default function Playground() {
  const favMovie = {title: "Office Space", year: 1999}
  top100Films.push(favMovie)

  const defaultProps = {
    options: top100Films,
    getOptionLabel: (option) => option.title
  };

  const [movies, setMovies] = useState([]);

  return (
    <div style={{ width: 300 }}>
      <Autocomplete
        {...defaultProps}
        id="select-on-focus"
        selectOnFocus
        renderInput={(params) => (
          <TextField {...params} label="movies" margin="normal" />
        )}
        onChange={(e, movie) => {
          if (movie) {
            setMovies([...movies, movie.title]);
          }
        }}
      />
    </div>
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  ...,
]

另见 my sandbox

您可以将 style 属性 添加到 ListItemText。

<ListItemText style={movie.style} primary={movie} />

top100Films 数组的项目更新为类似以下内容:

const top100Films = [
  { title: "The Shawshank Redemption", year: 1994, style: {color: 'red'}}
}

自动完成组件中添加:

renderOption={(option) => {
  if (option.hasOwnProperty("color"))
    return <div style={{ color: option.color }}>{option.title}</div>;
  return <div>{option.title}</div>;
}}

然后像这样编辑你的数据模型:

const top100Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972, color: "red" },
  { title: "The Godfather: Part II", year: 1974 },
  { title: "The Dark Knight", year: 2008 }
];

另请参阅我的分叉 codeSanbox