注意:代码中的两个select是级联的,切换第一个select的内容会设置第二个select的默认值
js部分
const [form] = Form.useForm();
const cityData = ['kafka1', 'testTwo'];
const logassetData = {
kafka1: ['logasset', '测试222'],
testTwo: ['测试一一一', '测试二二二'],
};
const [cities, setCities] = useState(logassetData[cityData[0]]);
const [secondCity, setSecondCity] = useState(logassetData[cityData[0]][0]);
const [open, setOpen] = useState(true);
//下拉框级联
const handleProvinceChange = (value, key) => {
//change时设置默认值
const fields = form.getFieldsValue();
const { ziduan } = fields; //ziduan是Form.List的name,需要拿出来重新组装下数据
if (value) {
Object.assign(ziduan[key], { logasset: logassetData[value][0] })
form.setFieldsValue({ ziduan })
setSecondCity(logassetData[value][0]);
setCities(logassetData[value]);//设置第二个下拉框的默认值
}
};
const onSecondCityChange = (value) => {
setSecondCity(value);
};
html部分
<Form className='formContainer' form={form}>
{/* 初始化默认展示两行 ,默认展示几行就在initialValue下写几个对象,好像可以设置数字,不过我没试过*/}
<Form.List name="ziduan" initialValue={[{ logasset: secondCity }, { logasset: secondCity }]}>
{(fields, { add, remove }) => (
<div className={'ziduan'}>
<Row>
<Col span={8} style={{ fontSize: 18, fontWeight: 600 }}>
表
</Col>
</Row>
{fields.map(({ key, name, ...restField }) => (
<div className='yuanBiao' style={{ display: 'flex', alignItems: 'center', marginTop: 15, position: 'relative' }} key={key}>
<Row
style={{ width: '100%' }}
>
<Col className="gutter-row" span={11}>
<Form.Item
name={[name, 'kafka1']}
{...restField}
rules={[
{
required: true,
message: 'kafka1不能为空',
},
]}
>
<Select
allowClear
options={cityData.map((province) => ({
label: province,
value: province,
}))}
onChange={(e) => handleProvinceChange(e, key)}
defaultValue={cityData[0]}
>
</Select>
</Form.Item>
</Col>
<Col className="gutter-row" span={11}>
<Form.Item
name={[name, 'logasset']}
{...restField}
rules={[
{
required: true,
message: 'logasset不能为空',
},
]}
>
<Select
allowClear
onChange={onSecondCityChange}
options={cities.map((city) => ({
label: city,
value: city,
}))}
>
</Select>
</Form.Item>
</Col>
<Col span={1}>
<div
onClick={() => remove(name)}
style={{ margin: '4px 0px 0px 12px' }}
>
<MinusCircleOutlined />
</div>
</Col>
</Row>
</div>
))}
<Row justify={'space-between'} align={'middle'} gutter={[16, 0]}>
<Col span={24}>
<Button
type="dashed"
onClick={() => add({ logasset: cities[0] })}
block
icon={<PlusOutlined />}
style={{ marginBottom: '20px' }}
>
</Button>
</Col>
<Col span={1} />
</Row>
</div>
)}
</Form.List>
</Form>
// rules只有在设置了name属性之后才生效,如不需要展示lable,则*也会消失,需要设置css样式即可
.target::before {
display: inline-block;
margin-right: 4px;
color: #ff4d4f;
font-size: 14px;
font-family: SimSun, sans-serif;
line-height: 1;
content: '*';
}