小编典典

React选择自动尺寸宽度

reactjs

使用时,react-select它不是根据选项值自动调整大小,而是width:100%如您在图片中看到的那样使用:

选择短值

选项简短:

getOptions() {
    return [
        { value: 'AND', label: 'AND' },
        { value: 'OR', label: 'OR' }
    ]
}

和产生它的代码:

<Select
    options={this.getOptions()}
    value={value}
    autosize={true}
    clearable={false}
    simpleValue
/>

是否可以react-select通过自动调整大小来显示这些值,所以选择框与选项长度相同,例如,我可以将此选择框居中<div>

更新了14.11.2017,
可以在此jsFiddle中看到完整的示例


阅读 711

收藏
2020-07-22

共1个答案

小编典典

解决方案1

您可以inline styles通过width根据所选选项的长度更新组件来利用React 。

让我进一步解释:说选定的值为HelloWorld。这串是长的10。我们可以猜测每个角色8px平均说出每个角色(总的猜测我一点都不知道)。因此,这个词的宽度大约是8*10=80px吧?另外,单词后面有一些控件(尖角和叉号),我们需要一些最小填充:它们在一起的100px宽度可能相同。然后就可以了:div的宽度应为( 8px * 10 letters ) + 100px = 180px

更准确地说,正确的公式如下所示:

(average_letter_size * selected_value.length) + other_elements_sizes

selected_value发生变化,所以做它length,因此div的宽度获取与新的总更新。

示例:如果选择的值为now Lorem Ipsum dolor sit amet,则长度为now 26。通过应用公式,我们得到更大的宽度:(8px * 26 letters) + 100px = 308px

为此,请使用以下代码段:

<Select
  style={{width: `${(8*this.state.selectedOption2.length) + 100}px`}}            
  className="select-custom-class"
  name="form-field-name"
  value={this.state.selectedOption2}
  options={options2}
  onChange={(value) => { this.setState({ selectedOption2: value.value }); }}
 />

如您所见,我添加了:

style={{width: `${(8*this.state.selectedOption2.length) + 100}px`}}

到您的组件。每当状态更新时,一切都会传播,包括组件的宽度。

请参阅此小提琴中的一个有效示例。

最终,您想调整规则并求平均值。我还建议您根据所选值中的大写和小写字母的数量来应用字母大小。

解决方案2 (编辑)

如果您愿意,我想出了一个纯CSS解决方案。应该针对您的设计进行更好的测试,但这应该可以:

// .Select-value comes with an absolute position to stack it below .Select-input
// we need to scratch that in order for us to be able to let the div grow depending on its content size
.Select-placeholder, .Select--single > .Select-control .Select-value {
  position: relative;
  padding-left: 0;
}

// All these 3 classes come with ugly "table" display...
.Select-control, .Select-clear-zone, .Select-arrow-zone {
  display: inherit;
}

// here is the trick: we display the wrapper as flex in order to make it fit in height
// we flip positions of .Select-value and .Select-input using row-reverse in order to have a nice input to the left and no to the right
.select-custom-class .Select-multi-value-wrapper {
  display: flex;
  flex-direction: row-reverse;
}

// we put our controls back to a better center position
.Select-clear-zone {
  position: absolute;
  top: 8px;
  right: 20px;
}

.Select-arrow-zone {
  position: absolute;
  top: 8px;
  right: 0px;
}

查看工作中的小提琴(为了更好地说明,我更改了一些示例)

告诉我你的想法。:)

2020-07-22