【发布时间】:2021-08-18 21:37:45
【问题描述】:
我正在尝试从数组中删除一个项目。
假设我有一个包含 5 个项目的数组:[0,1,2,3,4] 如果我删除第 5 项 [4],它可以正常工作。但是如果我删除项目 [1],对象 [2,3,4] 也会被删除。那我做错了什么?
这个函数增加了一个新的可拖动项
const addshootOutside = index => {
setShootOutside([
...shootOutside,
<Outside key={index} pageX={positionX} pageY={positionY}/>,
]);
};
这个函数删除一个可拖动的项目
const deleteHandler = index => {
const arr = shootOutside.filter((el, i) => index !== i)
setShootOutside(arr);
};
这里我称之为“deleteHandler”
const twoOptionAlertHandler = () => {
//function to make two option alert
Alert.alert(
//title
'Ta bort',
//body
'Är du säker på att du vill ta bort skott?',
[
{ text: 'OK', onPress: (index) => deleteHandler(index) },
{
text: 'Avbryt',
onPress: () => console.log('No Pressed'),
style: 'cancel',
},
],
{ cancelable: false }
//clicking out side of alert will not cancel
);
};
这是我的可拖动项目。
console.log(shootOutside);
const Outside = () => {
return (
<Draggable
x={200}
y={200}
onShortPressRelease={twoOptionAlertHandler}
renderSize={20}
renderColor="red"
renderText="x"
isCircle
onDragRelease={e => {
setPositionY(e.nativeEvent.pageY);
setPositionX(e.nativeEvent.pageX);
}}
/>
);
};
【问题讨论】:
-
查看 Array.prototype.shift() 或 stackoverflow.com/questions/5767325/…
-
@Alexander 你需要使用索引作为参数调用 deleteHandler
-
从 Alert.alert
deleteHandler的 onPress 方法调用时没有索引。因此删除数组中的所有内容 -
嗯,我更新了我的代码,但它仍然不起作用。我应该如何获取索引?
标签: reactjs react-native draggable