如何向 Material UI 选择选项添加图标?

IT技术 reactjs material-ui
2021-05-07 03:48:50

如何在Select选项中添加图标我尝试了很多次,但都没有奏效:

<option value={0}>&#xf083;Item One</option>
<option value={1}>
  <i class="fas fa-expand" />
  Item two
</option>

完整示例代码:

class IconInSelect extends Component {
  state = {
    value: 0
  };
  handleChange = name => event => {
    this.setState({ [name]: event.target.value });
  };
  render() {
    const { value } = this.state;
    const { classes } = this.props;
    return (
      <Select
        autoWidth
        native
        value={value}
        onChange={this.handleChange("value")}
        name="value"
        variant="filled"
        classes={{
          root: classes.selectEmpty,
          select: classes.select
        }}
      >
        <option value={0}>&#xf083;Item One</option>
        <option value={1}>
          <i class="fas fa-expand" />
          Item two
        </option>
        <option value={2}>Item three</option>
      </Select>
    );
  }
}

代码沙盒

3个回答

使用菜单项

class IconInSelect extends Component {
  ...
  render() {
    return (
      <Select>
        <MenuItem value="">
          <ListItemIcon>
            <InboxIcon />
          </ListItemIcon>
          <ListItemText primary="Inbox" />
        </MenuItem>
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
    );
  }
}

在此处输入图片说明

选择时无需换行即可更好地工作

<MenuItem value={10}>
    <div style={{ display: 'flex', alignItems: 'center' }}>
        <InboxIcon />
        <div>Inbox</div>
    </div>
</MenuItem>

只需在 InboxIcon 中使用自定义样式并根据需要设置边距

Dennis 的 asnwer 对我很有用,但如果您想更改图标和文本之间的空间,请使用以下代码:

import MuiMenuItem from '@mui/material/MenuItem';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import { styled } from '@mui/material/styles';

const MenuItem = styled(MuiMenuItem)(({ theme }) => ({
  '& .MuiSvgIcon-root': {
    marginRight: theme.spacing(1),
  },
}));
<Select {...}>
  {names.map((name) => (
    <MenuItem key={name} value={name}>
      <AccessTimeIcon />
      {name}
    </MenuItem>
  ))}
</Select>

代码沙盒演示