先看一下Cascader
组件单独使用回显时的例子
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Cascader } from 'antd';
const options = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
{
value: 'leifengta',
label: '雷峰塔',
}
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
function onChange(value) {
console.log(value);
}
ReactDOM.render(
<Cascader
defaultValue={['zhejiang', 'hangzhou', 'leifengta']}
options={options}
onChange={onChange}
style={{width:'300px'}}
/>,
document.getElementById('container'),
);
运行效果为:
显示很正常,但是在Form
表单中使用的话,由于受到Form.Item
上name
属性控制,这时在Cascader
组件上使用defaultValue
没有任何效果。
Form.Item
上使用有一个initialValue
属性,在这个上面添加了值之后,还是回显不出来。直接在Form
上添加initialValues
属性可以正常回显出来。
代码如下:
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import {
Form,
Cascader,
Button,
} from 'antd';
const residences = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const formItemLayout = {
labelCol: {
xs: {
span: 24,
},
sm: {
span: 8,
},
},
wrapperCol: {
xs: {
span: 24,
},
sm: {
span: 16,
},
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 16,
offset: 8,
},
},
};
const RegistrationForm = () => {
const [form] = Form.useForm();
const onFinish = values => {
console.log('Received values of form: ', values);
};
return (
<Form
{...formItemLayout}
form={form}
name="register"
onFinish={onFinish}
initialValues={{
residence: ['zhejiang', 'hangzhou', 'xihu'],
prefix: '86',
}}
scrollToFirstError
>
<Form.Item
name="residence"
label="Habitual Residence"
rules={[
{
type: 'array',
required: true,
message: 'Please select your habitual residence!',
},
]}
>
<Cascader options={residences} />
</Form.Item>
<Form.Item {...tailFormItemLayout}>
<Button type="primary" htmlType="submit">
Register
</Button>
</Form.Item>
</Form>
);
};
ReactDOM.render(<RegistrationForm />, document.getElementById('container'));
如有问题请联系我~
欢迎加入QQ群: