Antd select element: how can I disable typing?

大憨熊 提交于 2020-01-25 04:46:07

问题


I'm trying to use a select element with mode="multiple". I'd like for input to be disabled, meaning that a user can only choose between existing options, not enter text. How do I do this?

My element:

import { Select } from 'antd';
import 'antd/dist/antd.css';
const { Option, OptGroup } = Select;

<Select
                        defaultValue={['current', 'grower', 'variety', 'varietyP90']}
                        size={'large'}
                        style={{ width: '13rem' }}
                        onChange={value => this.setState({ yield: value })}
                        mode="multiple"
                        maxTagCount={0}
                        maxTagPlaceholder="Yield metrics">
                        <Option value="current">Current Yield</Option>
                        <Option value="grower">Grower Average</Option>
                        <Option value="variety">Variety Potential</Option>
                        <Option value="varietyP90">All growers' average</Option>
                    </Select>

回答1:


Unfortunately in v3.3 there is no way to hide the search input of Select in multiple mode.

We can set the input maxlength to zero and get the wanted result.

The offering solution is kind of a hack and I don't like it personally but I couldn't find any better solution. I tried to hide the input using css but that prevents to close the drop-list because the input is used as a trigger for closing the list on focus lost event.

class TagSelect extends Select {
  disableInput() {
    const selects = document.getElementsByClassName(`ant-select-search__field`)
    for (let el of selects) {
      el.setAttribute(`maxlength`, 0)
    }
  }
  componentDidMount() {
    this.disableInput()
  }
}

ReactDOM.render(
  <TagSelect
    defaultValue={['current']}
    size={'large'}
    style={{width: '100%'}}
    mode="multiple"
    placeholder="Yield metrics"
  >
    <Option value="current">Current Yield</Option>
    <Option value="grower">Grower Average</Option>
    <Option value="variety">Variety Potential</Option>
    <Option value="varietyP90">All growers' average</Option>
  </TagSelect>,
  document.getElementById("container")
)

The working demo you can check here.



来源:https://stackoverflow.com/questions/49278252/antd-select-element-how-can-i-disable-typing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!