import React, {useEffect, useState} from 'react';
import {CascaderSelect} from '@alifd/next';
import PropTypes from 'prop-types';
import {ProvinciaCascade} from '@api/publicInterface';
import useRequest from "@hooks/useRequest";
/**
- 1580043700@qq.com
- Zhang Jun
- createDate: 2020-12-11
- @param props
- @returns {*}
- @constructor 地址选择器,暂时不需要多选,后期有需求再加。
*/
const params = {token: sessionStorage.getItem('token')};
function Address(props) {
const {showSearch, onChange, disabled, value, dataSource, placeholder, resultAutoWidth, hasClear, depth} = props;
const [source, setSource] = useState([]);
const {data} = useRequest(ProvinciaCascade, params);
useEffect(() => {
if (!dataSource) {
setSource(formatData(data, depth));
} else {
setSource(dataSource);
}
}, [dataSource, data]);
return (
<CascaderSelect
hasClear={hasClear}
resultAutoWidth={resultAutoWidth}
showSearch={showSearch}
onChange={!!onChange && onChange}
dataSource={dataSource ?? source}
value={value && value[depth - 1]}
disabled={disabled}
placeholder={placeholder}
/>
);
}
const formatData = (data, depth) => {
if (!data || data.length === 0) {
return [];
}
return format(data, depth);
};
const format = (data, depth) => {
depth -= 1;
if (depth === -1) {
return null;
}
if (data) {
return data.map((v) => {
return {label: v.name, value: v.id, children: format(v.data, depth)};
});
} else {
return null;
}
};
Address.defaultProps = {
resultAutoWidth: false,
showSearch: false,
value: [],
disabled: false,
hasClear: true,
depth: 3,
};
Address.propTypes = {
onChange: PropTypes.func, //值改变
dataSource: PropTypes.array, //数据源,不传递则使用后台接口数据
value: PropTypes.array, //选中的数据
disabled: PropTypes.bool, //是否禁用
placeholder: PropTypes.string, //输入提示
depth: PropTypes.number, //地址显示深度1-3(省市区),默认显示3(省市区)
showSearch: PropTypes.bool, //显示搜素,默认false
hasClear: PropTypes.bool, //是否可清空,默认true
resultAutoWidth: PropTypes.bool, // 搜索结果列表是否和选择框等宽,默认false
};
export default Address;