qm-ui
Version:
千米公有云管理端UI基础组件库
110 lines (98 loc) • 2.61 kB
JavaScript
/**
* async net work tree select
* @author gcy[of1518]
* @date 2017/02
*/
import React, { Component } from 'react'
import { TreeSelect } from 'antd'
import { QMFetch } from 'qm-ux'
import { splitObject } from './_util/ObjectUtil'
const TreeNode = TreeSelect.TreeNode
const noop = () => undefined
export default class AsyncTreeSelect extends Component {
static defaultProps = {
host: '',
url: '',
optionKey: 'id',
optionValue: 'id',
optionTitle: 'name',
optionFilter: false,
value: [],
optionData: [],
onChange: noop,
}
constructor(props) {
super(props)
this.state = {
optionData: props.optionData || [],
}
}
componentWillMount() {
this.onFetch(this.props)
}
render() {
let { optionData } = this.state
let [{ url, optionKey, optionValue, optionTitle, optionFilter }, props] = splitObject(
this.props,
['host', 'url', 'optionKey', 'optionValue', 'optionTitle', 'optionFilter']
)
let optionNode = optionData
? optionData.map(v => {
return (
<TreeNode
key={v[optionKey]}
value={v[optionValue]}
title={v[optionTitle] || '-'}
disabled={
optionFilter && v && v.child && v.child instanceof Array && v.child.length > 0
}>
{v && v.child && v.child instanceof Array && v.child.length > 0
? this.pack(v.child)
: null}
</TreeNode>
)
})
: null
return <TreeSelect {...props}>{optionNode}</TreeSelect>
}
/**
* onChange
*/
onChange(value) {
this.props.onChange(value)
}
/**
* 服务器异步获取数据
*
* @param {Object} param
*/
onFetch(param) {
let { host, url } = param || {}
if (typeof url === 'string' && !!url.trim()) {
let self = this
QMFetch({ host, url }).then(res => {
let { data } = res || []
self.setState({ optionData: data.child || [] })
})
}
}
/**
* 数据封装
* @param {*} data
*/
pack = data =>
data.map(v => {
let { optionKey, optionValue, optionTitle, optionFilter } = this.props
return (
<TreeNode
value={v[optionValue]}
key={v[optionKey]}
title={v[optionTitle] || '-'}
disabled={optionFilter && v && v.child && v.child instanceof Array && v.child.length > 0}>
{v && v.child && v.child instanceof Array && v.child.length > 0
? this.pack(v.child)
: null}
</TreeNode>
)
})
}