解决方案 1
您可以inline styles通过width根据所选选项的长度更新组件来利用 React 。
让我进一步解释一下:假设选定的值为HelloWorld。该字符串的长度为10。我们可以猜测每个角色8px平均来说每个角色(总猜测我根本不知道)。因此,这个词的宽度大约是8*10=80px,对吗?此外,在单词(carret 和 cross)之后有一些控件,我们需要一些最小的填充:它们一起可能是100px宽度。然后你就知道了:你的 div 的宽度应该是( 8px * 10 letters ) + 100px = 180px.
更准确地说,正确的公式是这样的:
(average_letter_size * selected_value.length) + other_elements_sizes
当selected_value更改时,它的 也会更改,因此lengthdiv 的宽度会使用新的总数进行更新。
示例:如果选择的值为 now Lorem Ipsum dolor sit amet,则长度为 now 26。通过应用公式,我们得到了更大的宽度 : (8px * 26 letters) + 100px = 308px。
为了让它在react中工作,这里是一个片段:
<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;
}
查看工作小提琴(为了更好的说明,我更改了一些示例)
告诉我你的想法。:)