Ant Design React实现左右树穿梭框
时间: 2024-02-19 15:31:23 浏览: 28
Ant Design提供了Transfer组件,可以实现左右树穿梭框。具体实现步骤如下:
1. 安装Ant Design和React:
```
npm install antd --save
npm install react --save
```
2. 引入Transfer组件:
```
import { Transfer } from 'antd';
```
3. 创建数据源:
```
const dataSource = [
{
key: '1',
title: 'Node1',
description: 'Node1 description',
children: [
{
key: '1-1',
title: 'Child Node1',
description: 'Child Node1 description',
},
{
key: '1-2',
title: 'Child Node2',
description: 'Child Node2 description',
},
],
},
{
key: '2',
title: 'Node2',
description: 'Node2 description',
children: [
{
key: '2-1',
title: 'Child Node3',
description: 'Child Node3 description',
},
{
key: '2-2',
title: 'Child Node4',
description: 'Child Node4 description',
},
],
},
];
```
4. 创建Transfer组件并传入数据源:
```
<Transfer
dataSource={dataSource}
showSearch
targetKeys={targetKeys}
render={item => item.title}
/>
```
其中,`dataSource`为数据源,`showSearch`为是否显示搜索框,`targetKeys`为目标数据源,`render`为渲染每个节点的方法。
完整代码例子如下:
```
import React, { useState } from 'react';
import { Transfer } from 'antd';
const dataSource = [
{
key: '1',
title: 'Node1',
description: 'Node1 description',
children: [
{
key: '1-1',
title: 'Child Node1',
description: 'Child Node1 description',
},
{
key: '1-2',
title: 'Child Node2',
description: 'Child Node2 description',
},
],
},
{
key: '2',
title: 'Node2',
description: 'Node2 description',
children: [
{
key: '2-1',
title: 'Child Node3',
description: 'Child Node3 description',
},
{
key: '2-2',
title: 'Child Node4',
description: 'Child Node4 description',
},
],
},
];
function App() {
const [targetKeys, setTargetKeys] = useState([]);
const handleChange = (newTargetKeys) => {
setTargetKeys(newTargetKeys);
};
return (
<Transfer
dataSource={dataSource}
showSearch
targetKeys={targetKeys}
onChange={handleChange}
render={item => item.title}
/>
);
}
export default App;
```