【问题标题】:How to style a single element inside Material-ui autocomplete如何在 Material-ui 自动完成中设置单个元素的样式
【发布时间】:2021-09-02 09:51:43
【问题描述】:

我在 Material-UI 自动完成中有一系列电影,我想将我最喜欢的电影 - 办公空间 - 添加到这个数组中。有没有办法给这部电影自定义样式,让它有文字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

【问题讨论】:

    标签: reactjs autocomplete material-ui


    【解决方案1】:

    自动完成组件中添加这个:

    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

    【讨论】:

      【解决方案2】:

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

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

      将您的 top100Films 数组的项目更新为:

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

      【讨论】:

      • 对不起,我不清楚,但我希望将样式放在下拉菜单中,而不是
      猜你喜欢
      • 2022-08-09
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 2021-04-15
      • 2021-02-19
      相关资源
      最近更新 更多