BoxSelectionComponent.tsx
import React, { useState } from 'react'; import { Modal, Button, Table, message } from 'antd'; const BoxSelectionComponent: React.FC = () => { const [modalVisible, setModalVisible] = useState(false); const [selectedBoxes, setSelectedBoxes] = useState<string[]>([]); const boxes = ['A', 'B', 'C', 'D', 'E']; const showModal = () => { setModalVisible(true); }; const handleBoxSelect = (box: string) => { const isSelected = selectedBoxes.includes(box); if (isSelected) { const updatedSelection = selectedBoxes.filter((selectedBox) => selectedBox !== box); setSelectedBoxes(updatedSelection); } else { if (selectedBoxes.length < 3) { setSelectedBoxes([...selectedBoxes, box]); } else { message.warning('最多可以选中三个盒子'); } } }; const handleDelete = (box: string) => { const updatedSelection = selectedBoxes.filter((selectedBox) => selectedBox !== box); setSelectedBoxes(updatedSelection); if (updatedSelection.length === 0) { message.warning('至少选择一个盒子'); } }; const handleOk = () => { if (selectedBoxes.length === 0) { message.warning('至少选择一个盒子'); return; } // 处理选中的盒子,可以在这里进行进一步操作,比如提交数据 console.log('选中的盒子:', selectedBoxes); setModalVisible(false); }; const handleCancel = () => { setModalVisible(false); }; const columns = [ { title: '序号', dataIndex: 'index', key: 'index', render: (_: any, record: { index: number }) => record.index + 1, }, { title: '名称', dataIndex: 'name', key: 'name', }, { title: '操作', key: 'action', render: (_: any, record: { index: number; name: string }) => ( <> <Button type="link" onClick={() => handleView(record)}> 查看 </Button> <Button type="link" onClick={() => handleDelete(record.name)}> 删除 </Button> </> ), }, ]; const data = selectedBoxes.map((box, index) => ({ key: index, index, name: box, })); const handleView = (record: { index: number; name: string }) => { // 处理查看操作,可以根据需要展示盒子的详细信息等 console.log('查看盒子:', record); }; return ( <> <Button type="primary" onClick={showModal}> 打开Modal </Button> <Modal title="选择盒子" visible={modalVisible} onOk={handleOk} onCancel={handleCancel} > <div> {boxes.map((box) => ( <div key={box} style={{ border: '1px solid #ccc', padding: '10px', marginBottom: '10px', backgroundColor: selectedBoxes.includes(box) ? '#e6f7ff' : 'white', cursor: 'pointer', }} onClick={() => handleBoxSelect(box)} > {box} </div> ))} </div> </Modal> <Table columns={columns} dataSource={data} /> </> ); }; export default BoxSelectionComponent;