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

如何让MUI TextField Select选中项的Play Button正常触发功能

解决MUI v5 TextField Select选中项播放按钮点击触发下拉的问题

问题描述

使用MUI v5的TextField select组件,每个选项包含play button、avatar和选项文本,下拉列表内的元素功能正常,但选中项中的播放按钮点击时只会展开选项列表,无法触发预设的播放功能。

问题原因

点击选中项内的播放按钮时,事件会冒泡到上层的Select组件,触发了下拉列表展开的默认行为。

解决方案

阻止播放按钮的点击事件向上冒泡,避免触发Select的默认展开逻辑,以下是两种可行实现方式:

方式一:在自定义播放按钮组件内部处理

修改PlayAudioButton组件,在点击事件中添加stopPropagation(),从根源阻止事件冒泡:

import { IconButton } from '@mui/material';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import PauseIcon from '@mui/icons-material/Pause';

const PlayAudioButton = ({ sound, onPlay, isPlaying }) => {
  const handleClick = (e) => {
    e.stopPropagation();
    onPlay();
  };

  return (
    <IconButton onClick={handleClick}>
      {isPlaying ? <PauseIcon /> : <PlayArrowIcon />}
    </IconButton>
  );
};

方式二:在使用播放按钮时添加事件处理

如果无法修改PlayAudioButton组件源码,可在调用时通过onClick属性直接阻止冒泡:

<PlayAudioButton
  sound={voice}
  key={id}
  onPlay={() => console.log("play button " + id)}
  isPlaying={false}
  onClick={(e) => e.stopPropagation()}
/>

修改后的完整代码示例

import { TextField, MenuItem, Stack, Avatar, Typography } from '@mui/material';
import PlayAudioButton from './PlayAudioButton';

const StyledSelect = ({ ...props }) => {
  return (
    <TextField {...props} select fullWidth>
      {props.children}
    </TextField>
  );
};

export const AudioSelect = () => {
  return (
    <StyledSelect>
      {AUDIO_OPTIONS.map(({ id, name, avatar, voice }) => (
        <MenuItem key={id} value={id}>
          <Stack direction="row" spacing={1} alignItems="center">
            <PlayAudioButton
              sound={voice}
              key={id}
              onPlay={() => console.log("play button " + id)}
              isPlaying={false}
            />
            <Avatar src={avatar} />
            <Typography>{name}</Typography>
          </Stack>
        </MenuItem>
      ))}
    </StyledSelect>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:55:20