You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改MUI Autocomplete组件选中选项的背景样式

解决Material-UI Autocomplete选中选项背景色叠加问题

问题根源:你自定义的选项div是默认选项容器(带Mui-selected类的li元素)的子元素,选中时父元素的默认紫色背景会透过子元素的间隙或未覆盖区域显示,导致颜色叠加。以下是两种可行解决方案:


方案1:通过组件sx属性覆盖默认选中样式(推荐)

直接在Autocomplete组件上添加sx属性,覆盖选中选项的默认背景色,同时确保自定义div成为选项根容器:

<Autocomplete
  // 你的其他属性(如options、value、onChange等)
  sx={{
    '& .MuiAutocomplete-option.Mui-selected': {
      backgroundColor: 'yellow',
      // 可选:自定义hover状态背景色,避免hover时变回默认颜色
      '&:hover': {
        backgroundColor: 'yellow'
      }
    }
  }}
  renderOption={(params, { selected }) => {
    return (
      <div
        {...params} // 关键:传递该props,让div成为选项的根容器
        style={{
          height: '40px',
          display: 'flex',
          width: '100%',
          justifyContent: 'space-between',
          alignItems: 'center',
          padding: '0 16px', // 匹配默认选项的内边距,确保完全覆盖容器
        }}
      >
        <div style={{ gap: '1rem', alignItems: 'center', display: 'flex' }}>
          <div style={{ width: '10px', height: '10px', backgroundColor: 'green', borderRadius: '100%' }}></div>
          <h3 className={styles.optionsName}>
            {params.name}
            <span style={{ color: fontColors.greyDark }}>&nbsp;@{params.username}</span>
          </h3>
        </div>
        {selectedOptions.some(elem => elem.id === params.id) ? (
          <img src={selectedSign} />
        ) : null}
      </div>
    );
  }}
/>

方案2:在renderOption中动态控制背景色(适合动态场景)

利用sx属性的样式优先级,根据选中状态直接设置背景色,覆盖默认样式:

renderOption={(params, { selected }) => {
  return (
    <div
      {...params}
      sx={{
        height: '40px',
        display: 'flex',
        width: '100%',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: '0 16px',
        // 未选中时透明,选中时设为黄色
        backgroundColor: selected ? 'yellow' : 'transparent',
        // 强制覆盖Mui-selected类的默认背景
        '&.Mui-selected': {
          backgroundColor: 'yellow'
        },
        // 可选:自定义hover样式
        '&:hover': {
          backgroundColor: selected ? 'yellow' : '#f5f5f5'
        }
      }}
    >
      <div style={{ gap: '1rem', alignItems: 'center', display: 'flex' }}>
        <div style={{ width: '10px', height: '10px', backgroundColor: 'green', borderRadius: '100%' }}></div>
        <h3 className={styles.optionsName}>
          {params.name}
          <span style={{ color: fontColors.greyDark }}>&nbsp;@{params.username}</span>
        </h3>
      </div>
      {selectedOptions.some(elem => elem.id === params.id) ? (
        <img src={selectedSign} />
      ) : null}
    </div>
  );
}}

关键注意点

  1. 必须传递{...params}给renderOption返回的根div,确保div继承选项容器的className(包括Mui-selected)和必要属性。
  2. 设置padding匹配默认选项的内边距,避免父元素背景从间隙中透出。
  3. 利用sx或类选择器覆盖默认样式,确保自定义背景色优先级高于组件内置样式。

内容的提问来源于stack exchange,提问作者Muneeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 15:12:04