文章分类 其他 react.js 前端框架 前端 javascript ecmascript 阅读数 : 316 阅读时长 : 9分钟
//默认返回的
{
userName:'梦洁',
treeInfo:'leaf1-value'
}
//但是需要返回的如下
{
userName:'梦洁'
treeInfo:{
name:'leaf1-name',
value:'leaf1-value'
}
}
index.tsx
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;
SelfTreeSelect.tsx
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;
更多【react.js-Antd React Form.Item内部是自定义组件怎么自定义返回值】相关视频教程:www.yxfzedu.com