Antd Select
自带的搜索功能不少时候须要结合后端的接口,输入一个关键字的时候会自动更新选择器的选项. 下面列一些注意点react
选择器选项必须和每次更新的数据挂钩, 这个值能够经过state
,也能够经过props
拿到ios
再结合循环的方法例如map
遍历渲染optionsaxios
import React, { PureComponent, Fragment } from 'react' import { Select } from 'antd' import axios from 'axios' const Option = Select.Option; export default class AntSelect extends PureComponent{ ... handleSearch = (keywords) => { //请求后端搜索接口 axios('http://xxx.com/xxx', { keywords, }).then(data){ this.setState({ list: data }) } } render(){ const { list } = this.state; return( <Select mode="multiple" //多选模式 placeholder="请选择" filterOption={false} //关闭自动筛选 onSearch={this.handleSearch} > { list.map((item, index) => ( <Option key={index} value={item}>{item}</Option> )) } </Select> ) } ... }
上面就是一个简单的例子. 除了要动态渲染Options
之外, 还须要注意设置这个属性:
filterOption={false}
后端
若是不设置会致使即便拿到了最新的数据仍是依旧显示无匹配结果性能优化
由于filterOption
默认为true, 当你输入内容时候,会先在已有选项里面寻找符合项, 不管是否找到,都会从新渲染Options
,这样你接口请求的数据的渲染被覆盖了, 天然看不到结果了。因此须要把它关掉!antd
由于输入是属于高频js的操做, 因此咱们须要使用到函数节流或者函数防抖.函数
这里我直接使用函数防抖插件:lodash/debounce
性能
import debounce from 'lodash/debounce'; //在constructor统一绑定事件. 和常常使用的bind(this)同样 class AntSelect extends React.Component { constructor(props) { super(props); this.handleSearch = debounce(this.handleSearch, 500); } handleSearch = (value) => { ... } ... }
这样你在输入数据的500ms后才会触发handleSearch
函数,能够大幅度减小调取后台接口的次数!优化
antd已经给咱们封装好了加载状态的组件:<Spin />
.而后经过state控制其出现和消失this
class antdSelect extends React.Component { constructor(props) { super(props); this.state = { spinState: false, } } handleSearch = (keywords) => { ... //调用接口前清空数据, 出现加载icon this.setState({ list: [], spinState: true }) //请求后端搜索接口 axios('http://xxx.com/xxx', { keywords, }).then(data){ this.setState({ list: data, spinState: false }) } ... } render(){ const { list, spinState } = this.state; return( <Select ... notFoundContent={spinState ? <Spin /> : '暂无数据'} onSearch={this.handleSearch} ... > { list.map((item, index) => ( <Option key={index} value={item}>{item}</Option> )) } </Select> ) } }
更多的能够查看官方文档: 《Antd-Select》