首页 > 解决方案 > MUI 组件上的 fullWidth 和 className

问题描述

我想在 Material UI TextField 组件上同时使用 className 和 fullWidth 属性,但这似乎不起作用。

仅使用 className 可以正常工作,并且仅使用 fullWidth 也可以正常工作,但是当我尝试同时使用这两者时,它只会监听 className。

//Only className, works fine
<TextField
    id="date"
    label="Only className"
    type="date"
    defaultValue="2017-05-23"
    className={classes.textField}
    InputLabelProps={{
        shrink: true
    }}
/>
//Only fullWidth, works fine
<TextField
    id="date"
    label="Only fullWidth"
    type="date"
    defaultValue="2017-05-24"
    fullWidth={true}
    InputLabelProps={{
        shrink: true
    }}
/>
//Both, not working (only className is applied)
<TextField
    id="date"
    label="Both"
    type="date"
    defaultValue="2017-05-25"
    className={classes.textField}
    fullWidth={true}
    InputLabelProps={{
        shrink: true
    }}
/>

沙盒示例: https ://codesandbox.io/s/material-demo-0qqqd

标签: reactjstypescriptmaterial-ui

解决方案


在您的风格中,您通过提供自己的宽度TextField来覆盖道具 200px 。fullWidth

textField: {
  marginLeft: theme.spacing(1),
  marginRight: theme.spacing(1),
  width: 200
}

将其更改为:

textField: {
  marginLeft: theme.spacing(1),
  marginRight: theme.spacing(1),
  width: '100%'
}

或者

只需从 textField 样式中删除宽度

textField: {
  marginLeft: theme.spacing(1),
  marginRight: theme.spacing(1),
}

然后在你的 TextField 中使用fullWidth=true

  <TextField
    id="date"
    label="Birthday"
    type="date"
    defaultValue="2017-05-25"
    className={classes.textField}
    fullWidth={true}
    InputLabelProps={{
      shrink: true
    }}
  />

推荐阅读