MUI TextField自定义下拉图标后无法点击,寻求解决方案
MUI TextField Select自定义图标无法触发下拉的解决方案
问题出在你没有把MUI传递给IconComponent的关键props(包含下拉触发的点击事件)传递给自定义图标组件,导致点击图标时无法触发菜单展开。
核心修复:
修改SelectProps.IconComponent的写法,将它接收的props透传给你的NewIcon组件,确保点击事件能绑定到SVG元素上。
修改后的完整代码
/* eslint-disable react/jsx-props-no-spreading */ import React from 'react'; import { MenuItem, TextField } from '@mui/material'; import '../../assets/utils/_groupbySelect.scss'; const MuiSelect = ({ label, value, disabled, onChange, children, defaultValue, withNoneOption, className, }: MuiSelectProps) => { const NewIcon = (props) => ( <svg {...props} style={{ width: '11px', height: '11px', marginTop: '2px', cursor: 'pointer' }} className="sorter-dropdown" width="8" height="5" viewBox="0 0 8 5" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M1 1L4 3.5L7 1" stroke="#4C4C4D" strokeLinecap="round" /> </svg> ); return ( <TextField select defaultValue={defaultValue} label={label} disabled={disabled} className={className} value={value} onChange={onChange} variant="standard" SelectProps={{ // 关键:把IconComponent收到的props传递给NewIcon IconComponent: (props) => <NewIcon {...props} />, }} InputProps={{ disableUnderline: true, }} fullWidth size="small" > {withNoneOption ? isNoneOption : children} </TextField> ); }; export default MuiSelect;
额外排查点
- 检查自定义CSS:确认
_groupbySelect.scss中没有给.sorter-dropdown设置pointer-events: none,这个样式会阻止点击事件触发。 - 验证事件绑定:打开浏览器DevTools,查看SVG元素是否带有
onClick监听器,如果没有,说明props未正确传递。 - 备选方案:如果SVG本身点击区域过小,可将其包裹在MUI的
IconButton中,扩大可交互区域:
import { IconButton } from '@mui/material'; // ... const NewIcon = (props) => ( <IconButton size="small" {...props} sx={{ p: 0 }}> <svg style={{ width: '11px', height: '11px' }} className="sorter-dropdown" width="8" height="5" viewBox="0 0 8 5" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M1 1L4 3.5L7 1" stroke="#4C4C4D" strokeLinecap="round" /> </svg> </IconButton> );
内容的提问来源于stack exchange,提问作者Stiven Ballshi
相关产品推荐
相关产品推荐

