一、動態更新Options
基礎實現
選擇器選項必須和每次更新的數據掛鈎, 這個值可以通過state,也可以通過props拿到
再結合循環的方法例如map遍歷渲染options
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,這樣你接口請求的數據的渲染被覆蓋了, 自然看不到結果了。所以需要把它關掉!
二、函數防抖
性能優化
這里我直接使用函數防抖插件: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函數,可以大幅度減少調取后台接口的次數!
出現加載狀態
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》
