【问题标题】:Not able to change padding of material UI Select component无法更改材质 UI 选择组件的填充
【发布时间】:2019-12-26 22:36:09
【问题描述】:

我正在努力覆盖 Select 组件的默认填充以匹配我的其他文本字段的大小。我了解我需要修改嵌套组件,但一直无法找到可行的解决方案。

<div className='wifi-chooser-column'>
<TextField
    style={{margin: '6px'}} 
    label='SSID' 
    variant='outlined'
    size='small'
/>
<Select
    style={{margin: '6px', padding: '0px'}}
    variant='outlined'
    value={this.state.security}
    onChange={(event) => this.setState({security: event.target.value})}
    classes={{
        select: {
            padding: '10.5px 14px'
        }
    }}
>
    <MenuItem label='security' value='Unsecured'>Unsecured</MenuItem>
    <MenuItem value='WEP'>WEP</MenuItem>
    <MenuItem value='WPA2'>WPA2</MenuItem>
</Select>
<TextField 
    style={{margin: '6px'}} 
    label='Username' 
    variant='outlined'
    size='small'
/>
<TextField 
    style={{margin: '6px'}} 
    label='Password' 
    variant='outlined'
    size='small'
/>

Layout issue

【问题讨论】:

  • 你能提供一个包含你的代码的 CodeSandbox 吗?

标签: javascript css reactjs material-ui


【解决方案1】:

According to the doc,我们可以通过多种方式覆盖材质 UI 组件样式。

如果我们想以不同的方式偶尔覆盖Select 组件的填充,或者如果整个项目中不会重复此过程,我们可以简单地使用Overriding styles with classes 方法。这样,首先我们需要通过makeStyles为Select组件创建我们想要的填充,如下所示:

const useStyles = makeStyles((theme) => ({
  rootFirstSelect: {
    padding: "4px 0px"
  },
  rootSecondSelect: {
    padding: "10px 80px"
  }
}));

然后将其分配给组件的classes prop,通过修改根元素:

    const classes = useStyles();
    //Other part of the code
    return (
    //Other part of the code

    <Select
      classes={{ root: classes.rootFirstSelect }}
    //other props
    >

    //Other part of the code

    )

working sandbox example for this method

如果我们想为整个项目覆盖Select 组件的填充,Global theme variation 将防止重复。这样,我们应该通过createMuiTheme创建一个主题,如下所示,并在那里应用我们想要的更改:

const theme = createMuiTheme({
  overrides: {
    MuiSelect: {
      select: {
        padding: "4px 0px 10px 130px !important"
      }
    }
  }
});

然后将此主题作为道具传递给围绕整个项目的ThemeProvider 组件:

  <ThemeProvider theme={theme}>
    <Demo />
  </ThemeProvider>

working example in sandbox

【讨论】:

  • classes={{ root: classes.root }} 为我工作。
【解决方案2】:

我在文档中找到了另一种方法,这对我来说更容易使用:我没有使用 Select 组件,而是使用带有“select”道具的 TextField

cf:https://material-ui.com/components/text-fields/#select

<TextField
  id="standard-select-currency"
  select
  label="Select"
  value={currency}
  onChange={handleChange}
  helperText="Please select your currency"
>
  {currencies.map((option) => (
    <MenuItem key={option.value} value={option.value}>
      {option.label}
    </MenuItem>
  ))}
</TextField>

这允许您访问 TextField 属性,例如 margin="none"、margin="dense"

【讨论】:

  • 然后可以在 TextField 中添加 size="small"。这为我完成了工作。谢谢。
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 2019-04-17
  • 2022-06-28
  • 2021-01-06
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多