最近專案中要做一個拖動排序功能,首先想到的是之前專案中用過的antd自帶的tree和table的拖動排序,但是只能在對應的組建里使用,這里用的是自定義組件,隨意拖動排序,所以記錄一下實作流程
- react-dnd antd組件的拖動排序都是用的這個庫,使用比較靈活,但是要配置的東西比較多,需求復雜時使用這個庫;
class BodyRow extends React.Component { render() { const { isOver, connectDragSource, connectDropTarget, moveRow, ...restProps } = this.props; const style = { ...restProps.style, cursor: 'move' }; let { className } = restProps; if (isOver) { if (restProps.index > dragingIndex) { className += ' drop-over-downward'; } if (restProps.index < dragingIndex) { className += ' drop-over-upward'; } } return connectDragSource( connectDropTarget(<tr {...restProps} className={className} style={style} />), ); } } const rowSource = { beginDrag(props) { dragingIndex = props.index; return { index: props.index, }; }, }; const rowTarget = { drop(props, monitor) { const dragIndex = monitor.getItem().index; const hoverIndex = props.index; // Don't replace items with themselves if (dragIndex === hoverIndex) { return; } // Time to actually perform the action props.moveRow(dragIndex, hoverIndex); // Note: we're mutating the monitor item here! // Generally it's better to avoid mutations, // but it's good here for the sake of performance // to avoid expensive index searches. monitor.getItem().index = hoverIndex; }, }; const DragableBodyRow = DropTarget('row', rowTarget, (connect, monitor) => ({ connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), }))( DragSource('row', rowSource, connect => ({ connectDragSource: connect.dragSource(), }))(BodyRow), ); <DndProvider backend={HTML5Backend}> <Table columns={columns} dataSource={this.state.data} components={this.components} onRow={(record, index) => ({ index, moveRow: this.moveRow, })} /> </DndProvider> - react-beautiful-dnd 在專案中看到參考了這個庫,使用起來也不算復雜,就試著用了這個庫,不過只支持水平或垂直拖動,一行或者一列元素時可以使用,可惜這個需求時兩行多列元素,也沒辦法用;
<DragDropContext onDragEnd={this.onDragEnd}> <Droppable droppableId='phone-droppable'> {droppableProvided => ( <div ref={droppableProvided.innerRef} {...droppableProvided.droppableProps}> {this.state.phoneImages.map((image, index) => ( <Draggable key={image||'upload'} draggableId={image||'upload'} index={index}> {(provided, snapshot) => ( <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} style={{ ...provided.draggableProps.style, opacity: snapshot.isDragging ? 0.8 : 1, display: 'inline-block' }} > <img src=https://www.cnblogs.com/shenyuiOS/archive/2023/07/09/{img}/>
