本文基于antd组件库3.x版本的组件form以及select展开
论,如何把二级级联选择封成一个适合放进form.item里用的组件
我自己写的⬇️
import { useRequest } from 'ahooks';import { Select } from 'antd';import React, { useState } from 'react';import styles from './index.module.scss';interface CascadeSelectProps {value: any[];onChange: (e: any[]) => void;options: {disabled: boolean;};}function CascadeSelect(props: CascadeSelectProps) {const { value, options, onChange } = props;const { data: governArchData = {} } = useRequest<any>(API.datagoverncore.governArch.postGetGovernArch.request);const [cascadeValue, setCascadeValue] = useState<any[]>(value);const [secondData, setSecondData] = useState<any[]>([]);return (<div className={styles['cascade-select']}><SelectclassName={styles['cascade-select-item']}allowClearplaceholder="xxx"showArrow={true}showSearchdisabled={options.disabled}onChange={e => {setSecondData(governArchData[String(e)]);setCascadeValue([e, undefined]);onChange([e, undefined]);}}>{Object.keys(governArchData)?.map(item => (<Select.Option key={item} value={item}>{item}</Select.Option>))}</Select><SelectclassName={styles['cascade-select-item']}value={cascadeValue[1]}allowClearplaceholder="xxx"showArrow={true}showSearchdisabled={options.disabled}onChange={e => {setCascadeValue([cascadeValue[0], e]);onChange([cascadeValue[0], e]);}}>{secondData?.map((item: any) => (<Select.Option key={item?.id} value={item?.id}>{item?.cat2Name}</Select.Option>))}</Select></div>);}export default CascadeSelect;
如何在父组件中使用⬇️
<CascadeSelect
value={cascadeValue}
onChange={e => {
props.form.setFieldsValue({ business: e });
}}
options={{
disabled,
}}
/>
基本上就是,传一个总的值进去,这里设定成[undefined, undefined],然后change就调用函数修改
- 组件自身的value
- form里面的value(子传父用onChange修改
