sunmao-sdk
Version:
榫卯-开箱即用赋能-sdk
109 lines (98 loc) • 2.48 kB
JavaScript
;
import React, { useState, useEffect, useMemo } from "react";
import { Cascader } from "antd";
import { getFirstList } from "../../utils/commonUtils";
import { getCPDicList } from "../../utils/formUtils";
import { isEmpty, isNumber } from "lodash";
const SelectCascader = ({
onChange,
name,
value,
rootValue,
schema: { commonProps = {} },
options: uiOptions,
readOnly
}) => {
const {
requestFunc,
resetList,
okPath,
url,
params,
list,
key = "key",
text = "preName"
} = commonProps;
const [state, setState] = useState([]);
const [fetching, setFetch] = useState(false);
const names = name.split(",");
const namesLength = names.length;
useEffect(() => {
if (list) set(getCPDicList(list, key, text, "children"));
//需要网络请求
else if (url && requestFunc) {
post();
}
}, []);
const set = value => {
try {
if (resetList) {
// 支持重置list数据
value = resetList(value);
}
} catch {
} finally {
setState(value);
}
};
const post = async () => {
setFetch(true);
//组装请求参数
requestFunc(url, params, okPath).then(req => {
let list = getFirstList(req);
// 需要根据fieldNames 进行转换list数据
if (list) {
set(getCPDicList(list, key, text, "children"));
}
setFetch(false);
});
};
const handleChange = value => {
let obj = null;
if (namesLength > 1) {
obj = { ...rootValue };
obj[name] = value?.length ? value : null;
for (let i = 0; i < namesLength; i++) {
obj[names[i]] = value && value[i] ? value[i] : null;
}
}
onChange(name, value?.length ? value : null, obj);
};
const stringValue = useMemo(() => {
let retValue = value;
if (
!isEmpty(value) &&
value[value?.length - 1] &&
// !isString(value[value.length - 1]) // 多选时会有回显问题。
isNumber(value[value.length - 1])
) {
// 兼容历史数据,将 list<int> => list<string>
retValue = value.map(i => `${i}`);
}
return retValue;
}, [value]);
return (
<div style={{ width: "100%" }}>
<Cascader
style={{ width: "100%" }}
value={stringValue}
options={state}
onChange={handleChange}
placeholder="请选择"
disabled={readOnly}
{...uiOptions}
/>
</div>
);
};
export default SelectCascader;