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步走
- 设置拖拽根上下文
class App extends Component {
onDragEnd(result) {
if (result.destination) {
// doSomething
}
}
render() {
return (
<DragDropContext onDragEnd={this.onDragend}>
{this.props.children}
</DragDropContext>
)
}
}
onDragEnd
事件中的result
参数:
- 设置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>
- 设置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>
坑点
- 通常只需要一个
DragDropContext
组件 Draggable
组件必须是Droppable
组件的子组件Draggable
的draggableId
属性必须保证在Droppable
父组件下唯一,index
属性表明当前组件的顺序,也唯一。这个属性会在onDragEnd
事件结果中有所体现Droppable
组件内的Draggable
组件不需要拖拽特性,可以设置Draggable
组件的isDragDisabled
属性为true
- 可以设置
Droppable
组件的renderClone
属性自定义拖拽视图
END