rbd入坑指南

react-beautiful-dnd[drop and drag]入坑指南

Beautiful and accessible drag and drop for lists with React

相关链接:


React拖拽库调研

  • react-beautiful-dnd 23.9k⭐
  • react-dnd 15.9K⭐
  • react-grid-layout 13.7⭐
  • react-dropzone 8.2⭐
  • react-draggable 6.8k⭐
  • react-smooth-dnd 1.5k⭐

库分析

react-dnd:
两种使用方式:钩子函数 装饰器

react-beautiful-dnd:
组件


react-beautiful-dnd使用分3步走


  1. 设置拖拽根上下文
class App extends Component {
    onDragEnd(result) {
        if (result.destination) {
            // doSomething
        }
    }

    render() {
        return (
            <DragDropContext onDragEnd={this.onDragend}>
                {this.props.children}
            </DragDropContext>
        )
    }
}

onDragEnd事件中的result参数:
drag end result


  1. 设置Droppable父组件
<Droppable
    droppableId="ComList"
    isDropDisabled={true}
    renderClone={(provided, snapshot, rubric) => {
    const name = rubric.draggableId.split('-')[1]
    const PreviewComp = getPreviewComponent(name, {
        inlineStyle: {
            border: '1px dashed #e02200',
            backgroundColor: 'rgba(255, 255, 255, .75)'
        }
    })
    return (
        <div
        {...provided.draggableProps}
        {...provided.dragHandleProps}
        ref={provided.innerRef}
        >
        {PreviewComp}
        </div>
    )
    }}
>
    {(provided, snapshot) => (
    <div {...provided.droppableProps} ref={provided.innerRef}>
        <ComList />
        {provided.placeholder}
    </div>
    )}
</Droppable>

  1. 设置Draggable子组件
<Draggable
    draggableId={`ComItem-${this.props.name}-${this.props.index}`}
    index={this.props.index}
    isDragDisabled={false}
>
    {(provided, snapshot) => (
    <div
        ref={provided.innerRef}
        {...provided.draggableProps}
        {...provided.dragHandleProps}
        className={c(s.wrapper, !addable && s.disable)}
        onClick={this.add}
    >
        <CurrentIcon style={{ fontSize: '20px' }} />
        {userName}
    </div>
    )}
</Draggable>

坑点

  1. 通常只需要一个DragDropContext组件
  2. Draggable组件必须是Droppable组件的子组件
  3. DraggabledraggableId属性必须保证在Droppable父组件下唯一, index属性表明当前组件的顺序,也唯一。这个属性会在onDragEnd事件结果中有所体现
  4. Droppable组件内的Draggable组件不需要拖拽特性,可以设置Draggable组件的isDragDisabled属性为true
  5. 可以设置Droppable组件的renderClone属性自定义拖拽视图

END

posted @ 2021-06-15 11:11  西河  阅读(26)  评论(0编辑  收藏  举报