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

如何用MUI和React创建含自定义函数组件选项的下拉框

实现带头像的个性化下拉框

你用NativeSelect的方式行不通,因为原生<select>的<option>只能渲染文本内容,没法嵌入React组件,所以自定义的OwnerList会显示异常。要实现带头像和信息的下拉选项,推荐用Material-UI的Select组件配合MenuItem,它支持完全自定义选项内容。

解决方案代码

import { useState } from 'react';
import { Box, FormControl, InputLabel, Select, MenuItem, Avatar, Typography, IconButton } from '@mui/material';
import SwapVertIcon from '@mui/icons-material/SwapVert';

const OwnerList = ({ name, avatarSrc }) => {
  return (
    <Box
      sx={{ display: 'flex', alignItems: 'center', gap: 1 }}
      className="owner-container"
    >
      <Avatar src={avatarSrc} sx={{ width: 40, height: 40 }} />
      <Box>
        <Typography sx={{ fontSize: 14 }}>{name}</Typography>
      </Box>
      <Box className='owner-iconbutton-container'>
        <IconButton className='owner-iconbutton' size="small">
          <SwapVertIcon />
        </IconButton>
      </Box>
    </Box>
  );
};

export const OwnerListDropdown = () => {
  // 管理选中值的状态
  const [selectedUser, setSelectedUser] = useState(30);

  const handleChange = (event) => {
    setSelectedUser(event.target.value);
  };

  // 模拟用户数据
  const users = [
    { value: 10, name: 'Robert Douglas Thomas Pattinson', avatarSrc: 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/actor-robert-pattinson-attends-the-opening-ceremony-of-the-news-photo-1588147075.jpg?crop=1.00xw:0.669xh;0,0.0920xh&resize=480:*' },
    { value: 20, name: 'Another User', avatarSrc: 'https://example.com/another-avatar.jpg' },
    { value: 30, name: 'Third User', avatarSrc: 'https://example.com/third-avatar.jpg' }
  ];

  return (
    <Box sx={{ minWidth: 300 }}>
      <FormControl fullWidth>
        <InputLabel variant="standard" htmlFor="custom-select">
          User
        </InputLabel>
        <Select
          value={selectedUser}
          onChange={handleChange}
          inputProps={{
            name: 'User',
            id: 'custom-select',
          }}
        >
          {users.map(user => (
            <MenuItem key={user.value} value={user.value}>
              <OwnerList name={user.name} avatarSrc={user.avatarSrc} />
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </Box>
  );
};

关键说明

  • 替换NativeSelect为MUI的Select组件:它是完全由React渲染的组件,支持在MenuItem中嵌入任何自定义React元素
  • 用MenuItem包裹自定义选项内容:每个MenuItem对应一个下拉选项,里面可以放Avatar、文本、按钮等任意组件
  • 状态管理:通过useState维护选中值,实现受控组件(也可以用非受控,但受控更易管理)
  • 优化OwnerList:把用户信息做成props传入,方便复用不同用户的数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:20:29