#reactjs #react-beautiful-dnd
#reactjs ( реакция ) #реагировать-красиво-dnd #reactjs
Вопрос:
У меня есть массив объектов, который находится в этом формате
sampleItemDetail: [
{
type: 'Take out the garbage',
isBox1: true
},
{
type: 'Watch my favorite show',
isBox1: true
},
{
type: 'Charge my phone',
isBox2: true
},
{
type: 'Cook dinner',
isBox1: true
},
{
type: 'Take out the garbage1',
isBox2: true
},
{
type: 'Watch my favorite show2',
isBox1: true
},
{
type: 'Charge my phone3',
isBox1: true
}
]
Я использую react-beautiful-dnd для перетаскивания этого массива объектов. Я хочу иметь возможность назначать индекс на основе перетаскивания, а также флаг isBox.
Каков будет наиболее эффективный способ сделать это? Я в замешательстве, так как состояние не имеет индекса. Нужно ли мне добавлять свойство index к элементам, чтобы это произошло?
https://codesandbox.io/s/react-beautiful-dnd-tutorial-forked-ij1oq?file=/src/index.js
Ответ №1:
Вы можете попробовать это, предполагая, что размер массива элементов всегда равен 3:
// Create a local shallow copy of the state
var items = this.state.items.slice()
// Find the index of the selected item within the current items array.
var selectedItemName = this.state.selected;
function isSelectedItem(element, index, array) {
return element.id === selectedItemName;
};
var selectedIdx = items.findIndex(isSelectedItem);
// Extract that item
var selectedItem = items[selectedIdx];
// Delete the item from the items array
items.splice(selectedIdx, 1);
// Sort the items that are left over
items.sort(function(a, b) {
return a.id < b.id ? -1 : 1;
});
// Insert the selected item back into the array
items.splice(1, 0, selectedItem);
// Set the state to the new array
this.setState({items: items});
Комментарии:
1. Я смог заставить его почти работать, но по какой-то причине продолжал терять элементы codesandbox.io/s /…