【问题标题】:How to use drag and drop in ant design?蚂蚁设计中如何使用拖放?
【发布时间】:2022-01-12 17:18:04
【问题描述】:

我想要的是一个关于如何使我的表格的拖放正常工作的示例,但我不知道如何使其在(功能组件)中工作

我的代码:

   function Preview() {
      const { name } = useParams();
      const [fieldsOfForm, setFieldsOfForm] = useState([]);
      const [selectedForm, setSelectedForm] = useState([]);

      const columns = [
        {
          title: 'Posição',
          dataIndex: 'pos',
          width: 30,
          className: 'drag-visible',
          render: () => 
          <MenuOutlined style={{ cursor: 'grab', color: '#999' }}/>
        },
        {
          title: "Form Name",
          dataIndex: "field",
          key: "field",
          render: (text) => <a>{text}</a>,
        },
        {
          title: "Tipo",
          dataIndex: "fieldtype",
          key: "fieldtype",
        },
      ];
 
      useEffect(() => {
        let mounted = true;
        let loadingStates = loading;
        if (mounted) {
          setFieldsOfForm(location.state);
          loadingStates.allFields = false;
          setLoading(false);
        }
        return () => (mounted = false);
      }, [selectedForm]);
    
    
      return (
           //Some jsx....
             <Row gutter={1}>
                <Col span={1}></Col>
                  <Table dataSource={fieldsOfForm} 
                    columns= {columns}/>
              </Row>
            // More jsx...          
      );
    }
    
    export default Preview; 

我在互联网上找到的关于从 antd 的库中拖放的所有内容都在 class component 中,但我想让它在我的函数式组件中工作。

我找到的示例: multi row drag-able table (antd)

如果有人已经尝试过并且可以帮助我,我想要函数组件中的一些示例?

【问题讨论】:

    标签: javascript reactjs jsx antd


    【解决方案1】:

    这是一个功能性工作示例:

    import React from "react";
    import "antd/dist/antd.css";
    import { Table } from "antd";
    import {
      sortableContainer,
      sortableElement,
      sortableHandle
    } from "react-sortable-hoc";
    import { MenuOutlined } from "@ant-design/icons";
    
    const data = [
      {
        key: "1",
        name: "John Brown",
        age: 32,
        address: "New York No. 1 Lake Park",
        index: 0
      },
      {
        key: "2",
        name: "Jim Green",
        age: 42,
        address: "London No. 1 Lake Park",
        index: 1
      },
      {
        key: "3",
        name: "Joe Black",
        age: 32,
        address: "Sidney No. 1 Lake Park",
        index: 2
      },
      {
        key: "4",
        name: "4",
        age: 32,
        address: "New York No. 1 Lake Park",
        index: 3
      },
      {
        key: "5",
        name: "5",
        age: 42,
        address: "London No. 1 Lake Park",
        index: 4
      },
      {
        key: "6",
        name: "6",
        age: 32,
        address: "Sidney No. 1 Lake Park",
        index: 5
      }
    ];
    
    const DragHandle = sortableHandle(({ active }) => (
      <MenuOutlined style={{ cursor: "grab", color: active ? "blue" : "#999" }} />
    ));
    
    const SortableItem = sortableElement((props) => <tr {...props} />);
    const SortableContainer = sortableContainer((props) => <tbody {...props} />);
    
    function SortableTable() {
      const [dataSource, setDataSource] = React.useState(data);
      const [selectedItems, setSelectedItems] = React.useState([]);
    
      const getColumns = () => {
        return [
          {
            title: "Sort",
            dataIndex: "",
            width: 30,
            className: "drag-visible",
            render: (d, dd, i) => (
              <>
                <DragHandle active={selectedItems.includes(i)} />
              </>
            )
          },
          {
            title: "Name",
            dataIndex: "name",
            className: "drag-visible"
          },
          {
            title: "Age",
            dataIndex: "age"
          },
          {
            title: "Address",
            dataIndex: "address"
          }
        ];
      };
      const merge = (a, b, i = 0) => {
        let aa = [...a];
        return [...a.slice(0, i), ...b, ...aa.slice(i, aa.length)];
      };
      const onSortEnd = ({ oldIndex, newIndex }) => {
        let tempDataSource = dataSource;
    
        if (oldIndex !== newIndex) {
          if (!selectedItems.length) {
            let movingItem = tempDataSource[oldIndex];
            tempDataSource.splice(oldIndex, 1);
            tempDataSource = merge(tempDataSource, [movingItem], newIndex);
          } else {
            let filteredItems = [];
            selectedItems.forEach((d) => {
              filteredItems.push(tempDataSource[d]);
            });
            let newData = [];
            tempDataSource.forEach((d, i) => {
              if (!selectedItems.includes(i)) {
                newData.push(d);
              }
            });
            tempDataSource = [...newData];
            tempDataSource = merge(tempDataSource, filteredItems, newIndex);
          }
          setDataSource(tempDataSource);
          setSelectedItems([]);
        }
      };
    
      const DraggableContainer = (props) => (
        <SortableContainer
          useDragHandle
          disableAutoscroll
          helperClass="row-dragging"
          onSortEnd={onSortEnd}
          {...props}
        />
      );
    
      const DraggableBodyRow = ({ className, style, ...restProps }) => {
        // function findIndex base on Table rowKey props and should always be a right array index
        const index = dataSource.findIndex(
          (x) => x.index === restProps["data-row-key"]
        );
        return (
          <SortableItem
            index={index}
            {...restProps}
            selected={selectedItems.length}
            onClick={(e) => {
              if (e.ctrlKey || e.metaKey) {
                selectedItems.includes(index)
                  ? selectedItems.splice(selectedItems.indexOf(index), 1)
                  : selectedItems.push(index);
                setSelectedItems(selectedItems);
              } else {
                setSelectedItems([]);
              }
            }}
          />
        );
      };
    
      return (
        <>
          <h3>"CNTRL + Click" to select multiple items</h3>
    
          <Table
            pagination={false}
            dataSource={dataSource}
            columns={getColumns()}
            rowKey="index"
            components={{
              body: {
                wrapper: DraggableContainer,
                row: DraggableBodyRow
              }
            }}
          />
          {selectedItems.length ? <>{selectedItems.length} items selected </> : ""}
        </>
      );
    }
    
    

    你可以在Sandbox玩它

    【讨论】:

    • 非常感谢你拯救了我的一天
    • 我很高兴,您可以通过比较您共享的示例链接和我上面的示例之间的变化来学习如何自己从基于类的组件转换为功能组件
    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 2021-12-12
    • 2019-04-06
    • 2020-05-11
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 2020-07-12
    相关资源
    最近更新 更多