Topic: Realize the basic functions of antd shuttle box
The realization of antd's shuttle frame has the following points:
- The data is divided into two parts, source-left side, target-right side
- The options are shuttled in the left and right boxes, which are actually data maintenance for adding and deleting the two arrays of source and target
The following is the complete implementation, online demo
import React, { useState } from "react";
import "./styles.css";
export default function Transfer(props) {
const [source, setSource] = useState(props.dataSource);
const [target, setTarget] = useState([]);
const [sourceSelectedKeys, setSourceSelectedKeys] = useState([]);
const [targetSelectedKeys, setTargetSelectedKeys] = useState([]);
const onSelectChange = (key, type, e) => {
if (type === "source") {
setSourceSelectedKeys([...sourceSelectedKeys, key]);
} else {
setTargetSelectedKeys([...targetSelectedKeys, key]);
}
};
const moveToRight = () => {
const dataSourceCpy = [...source];
const moveItem = dataSourceCpy.filter((item) =>
sourceSelectedKeys.includes(item.key)
);
const newSource = dataSourceCpy.filter(
(item) => !sourceSelectedKeys.includes(item.key)
);
setTarget([...moveItem, ...target]);
setSource(newSource);
setSourceSelectedKeys([]);
};
const moveToLeft = () => {
const targetCpy = [...target];
const moveItem = targetCpy.filter((item) =>
targetSelectedKeys.includes(item.key)
);
const newTarget = targetCpy.filter(
(item) => !targetSelectedKeys.includes(item.key)
);
setTarget(newTarget);
setSource([...moveItem, ...source]);
setTargetSelectedKeys([]);
};
const handleTransfer = (type) => {
if (type === "right") {
moveToRight();
} else {
moveToLeft();
}
};
return (
<div className="container">
<div className="dataSource">
{source.map((item) => {
return (
<div key={item.key}>
<input
type="checkbox"
name={item.title}
onChange={(e) => {
onSelectChange(item.key, "source", e);
}}
/>
<label htmlFor={item.title}>{item.title}</label>
</div>
);
})}
</div>
<div className="operation">
<button
onClick={() => {
handleTransfer("right");
}}
>
{">"}
</button>
<button
onClick={() => {
handleTransfer("left");
}}
>
{"<"}
</button>
</div>
<div className="target">
{target.map((item) => {
return (
<div key={item.key}>
<input
type="checkbox"
name={item.title}
onChange={(e) => {
onSelectChange(item.key, "target", e);
}}
/>
<label htmlFor={item.title}>{item.title}</label>
</div>
);
})}
</div>
</div>
);
}
.container {
display: flex;
}
.dataSource {
border: 1px solid black;
width: 200px;
height: 300px;
}
.operation {
display: flex;
flex-direction: column;
}
.target {
border: 1px solid black;
width: 200px;
height: 300px;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。