根据标签大小设置材料UI选择的宽度

时间:2018-07-18 18:11:57

标签: reactjs material-ui

我有一个select

<FormControl className={classes.formControl}>
    <InputLabel htmlFor="age-native-simple">{this.props.label}</InputLabel> 
    <Select
            native
            value={this.state.value}
            onChange={this.handleSelectChange('value')}
        inputProps={{
            name: this.props.label,
            id: this.props.id,
        }}
        >
        {this.buildSelectOptions(this.props.options)}
    </Select>
                        {(this.props.helperText)?<FormHelperText>{this.props.helperText}</FormHelperText>:null}
</FormControl>

formControl类如下:

formControl: {
    margin: 0,
    fullWidth: true,
    backgroundColor: '#9ee',
    wrap: 'nowrap'
},

它工作得相当好-尽可能缩小自身,同时仍显示最大的option值。

不幸的是,当InputLabel的长度超过选择的options的内容时...标签会包裹起来,看起来很糟糕。

如何避免选择的内容包装输入标签?我希望它可以根据需要简单地扩展选择范围,如果可能的话,在option列表中有很长的条目时也可以这样做。设置“ minWidth”不是我的首选解决方案,原因有很多(主要是,一堆不同的东西使用此组件,并且计算所有组件的minWidth会很困难)

1 个答案:

答案 0 :(得分:4)

编辑:我在这里误解了这个问题。我认为问题出在菜单项包装上,我的答案可以解决。该问题的正确而简单的解决方法是,您在formControl类中缺少display: 'flex'

像这样:

  formControl: {
    margin: 0,
    fullWidth: true,
    backgroundColor: '#9ee',
    display: 'flex',
    wrap: 'nowrap'
  },

这是工作中的sandbox

看起来<Select/>具有autoWidth属性,您可以设置该属性来实现。默认值为false

从文档中:

  

如果为true,则弹出窗口的宽度将根据   菜单中的项目,否则至少为宽度   选择输入的内容。

它的用法如下:

 <Select
    native
    autoWidth={true}
    value={this.state.value}
    onChange={this.handleSelectChange('value')}
    inputProps={{
        name: this.props.label,
        id: this.props.id,
    }}
    >
    {this.buildSelectOptions(this.props.options)}
 </Select>
相关问题