本文介绍了如何设置Material-UI MenuItem宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有Material-UI的菜单,为什么要使用整个屏幕宽度?如何限制仅使用文本长度所需的空间?

I have a Menu with Material-UI, why is the whole screen width used? How can I limit to use only the text length needed space?

我试图将div元素放在MenuList周围,但这没有帮助.

I tried to put div element around MenuList but it did not help.

class MainPage extends React.Component {
  render() {
    return (
      <div>
      <MenuList>
        <MenuItem>Profile</MenuItem>
        <MenuItem>My account</MenuItem>
        <MenuItem>Logout</MenuItem>
      </MenuList>

推荐答案

使用ThemeProvider,并覆盖MuiList-root宽度:

Use ThemeProvider, and override the MuiList-root width:

import { createMuiTheme } from '@material-ui/core/styles';
import { ThemeProvider } from '@material-ui/styles';

const theme = createMuiTheme({
  overrides: {
    MuiList: {
      root:{
      width: 'fit-content'
      }
    }
  }
});

并且比您的组件中的

 <div>
      <ThemeProvider theme={theme}>
        <MenuList>
          <MenuItem>Profile</MenuItem>
          <MenuItem>My account</MenuItem>
          <MenuItem>Logout</MenuItem>
        </MenuList>
      </ThemeProvider>
</div>

有效的CodeSandbox示例: https://codesandbox.io/s/material -demo-5sbjw?fontsize = 14

Working CodeSandbox example: https://codesandbox.io/s/material-demo-5sbjw?fontsize=14

这篇关于如何设置Material-UI MenuItem宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:16