反应选择自动尺寸宽度

新手上路,请多包涵

当使用 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 中看到

原文由 Orbitum 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

解决方案 1

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

让我进一步解释一下:假设选择的值为 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 发生变化时,它的 length --- 也会发生变化,因此 div 的宽度会随着新的总数而更新。

示例:如果现在选择的值是 Lorem Ipsum dolor sit amet ,那么现在的长度是 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`}}

到您的组件。每当状态更新时,都会传播所有内容,包括组件的宽度。

请参阅this fiddle 中的一个工作示例。

最终,您希望根据需要微调规则和平均值。我还建议您根据所选值中大写和小写字母的数量来应用字母大小。

解决方案 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;
}

查看一个工作 小提琴(我更改了一些示例以获得更好的说明)

告诉我你的想法。 :)

原文由 Jona Rodrigues 发布,翻译遵循 CC BY-SA 4.0 许可协议

内联样式对我不起作用。我只是将 Select 组件包装在一个 div 中,并为 div 提供了我想要的宽度。

 <div style={{width: '300px'}}>
  <Select
    menuPlacement="auto"
    menuPosition="fixed"
    etc, etc..
  />
</div>

原文由 tjgragg 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进