- 在线演示
- https://stackblitz.com/edit/stackblitz-starters-xwtwyz?file=src%2FSelfTreeSelect.tsx
需求
- 当我们点击提交,需要返回用户名和选中树的id信息,但是,我不关要返回树的id信息,还需要返回选中树的名称
{
userName:'梦洁',
treeInfo:'leaf1-value'
}
{
userName:'梦洁'
treeInfo:{
name:'leaf1-name',
value:'leaf1-value'
}
}
做法
了解下Form.Item怎么获取值的
实现自定义
import {Form,Input,Button} from "antd";
import SelfTreeSelect from "../../component/SelfTreeSelect";
const Index = () => {
const [form] = Form.useForm();
const onFinish = (values: any) => {
console.log('Success:', values);
};
/*初始化值*/
const setInitValue = () => {
form.setFieldsValue({
username:'梦洁',
treeInfo:{
value:'leaf1-value',
//这里传入数组是因为对于树来说,可以多选,所以后端保存的值也可能是数组,
list:['leaf1-title']
}
})
}
return (
<>
<Form
form={form}
name="basic"
onFinish={onFinish}
>
<Form.Item
label="用户名"
name="username"
rules={[{required: true, message: 'Please input your username!'}]}
>
<Input/>
</Form.Item>
{/*自定义组件*/}
<Form.Item
name="treeInfo"
label="树的信息"
>
<SelfTreeSelect/>
</Form.Item>
<Form.Item >
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
<Button onClick={setInitValue}>点击我初始化值</Button>
</>
);
};
export default Index;
import React, {useEffect, useState} from 'react';
import { TreeSelect } from 'antd';
const treeData = [
{
value: 'parent 1-value',
title: 'parent 1-title',
children: [
{
value: 'parent 1-0-value',
title: 'parent 1-0-title',
children: [
{
value: 'leaf1-value',
title: 'leaf1-title',
},
{
value: 'leaf2-value',
title: 'leaf2-title',
},
],
},
],
},
];
/* 默认值,初始值?form设置值 */
const SelfTreeSelect = (props:any) => {
const { value,onChange } = props;
console.log('查看传入的值',props)
/*这里简单演示下回填值*/
useEffect(() => {
setCurrentValue(value?.list[0])
}, [props]);
/*内部值,这样子就可以设置这个值来实现默认值的操作了*/
const [currentValue, setCurrentValue] = useState<string>();
const onSelectChange = (newValue: string,selectList:never[]) => {
console.log('输出新值第一个为选中的value,第二个为选中的title数组',newValue,selectList)
setCurrentValue(newValue);
onChange({
value:newValue,
list:selectList,
})
};
return (
<TreeSelect
showSearch
style={{ width: '100%' }}
value={currentValue}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="Please select"
allowClear
treeDefaultExpandAll
onChange={onSelectChange}
treeData={treeData}
/>
);
};
export default SelfTreeSelect;