reactjs - React Beautiful Dnd:删除项目后,源和目标索引未定义
问题描述
我是新手react.js
,正在尝试使用
react-beautiful-dnd
. 多次尝试后我无法找到问题,下面是代码,拖放很好,但拖放后list
基本上没有重新排序,在onDragEnd
函数result.source.index
中result.destination.index
是undefined
。
import React from 'react';
import ReactDOM from 'react-dom'
import {
DragDropContext, Droppable, Draggable
} from 'react-beautiful-dnd'
//data
const getItems = (count) => Array.from({length: count}, (v, k) => k).map(k => ({
id: `item-${k}`,
content: `item ${k}`
}))
/** Reorder an array, moving the item at $startIndex to $endIndex. */
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list)
const [removed] = result.splice(startIndex, 1)
result.splice(endIndex, 0, removed)
return result
}
// inline style
const grid = 8
const getItemStyle = (dragabbleStyle, isDragging) => ({
userSelect: 'none',
padding: grid * 2,
marginBotom: grid,
background: isDragging ? 'lightgreen': 'grey',
...dragabbleStyle
})
const getListStyle = (isDraggingOver) => ({
background: isDraggingOver ? 'lightblue' : 'lightgrey',
padding: grid,
width: 250
})
class AppDnD extends React.Component {
constructor(props) {
super(props)
this.state = {
items: getItems(10)
}
}
onDragEnd = (result) => {
if(!result.destination) {return}
console.log(result)
const items = reorder (
this.state.items,
result.source.index,
result.destination.index,
)
this.setState({items})
}
render() {
return (
<DragDropContext onDragEnd={this.onDragEnd}>
<Droppable droppableId="droppable">
{(provided, snapshot) => (
<div
ref={provided.innerRef}
style={getListStyle(snapshot.isDraggingOver)}
>
{this.state.items.map(item => (
<Draggable
key={item.id}
draggableId={item.id}
>
{(provided, snapshot) => (
<div>
<div
ref={provided.innerRef}
style={
getItemStyle(
provided.draggableProps.style,
snapshot.isDragging
)}
{...provided.dragHandleProps}
{...provided.draggableProps}
>
{item.content}
</div>
{provided.placeholder}
</div>
)}
</Draggable>
))}
</div>
)}
</Droppable>
</DragDropContext>
)
}
}
export default AppDnD;
有人可以告诉我拖放是如何工作的吗react-beautiful-dnd
?我的实际目标是对表格进行拖放行为,如果有人为它提供一些积分,那就太好了。
解决方案
我找到了解决方案,在<Draggable>
组件中我们需要定义id={i}
属性。整个语句看起来像这样 `
推荐阅读
- angular - Angular 8:无法在选择框中获取所选值
- python - 我如何访问 gsp 电子表格中的工作表名称。工作表()
- airflow - 在时区感知 DAG 中,next_ds 在夏令时期间的行为是否正确?
- ios - 我需要以编程方式在智能电视上显示来自 iphone 的视频
- c# - Audit.Net MVC - 如何解决 NullReferenceException?
- reactjs - 为什么在输入更改时重新渲染功能组件中的所有元素
- javascript - moment.utc('date string').format('DD-MMM-YYYY') 返回上一个日期
- c# - 在不同的机器 C# 中生成和签署证书
- jquery - JQuery .nextUntil() 选择标题进入 li
- javascript - 如何创建多个popper实例?