我的问题与此处相同:https://github.com/tongyy/react-native-draggable/issues/92 反正我重新写: 用法:我使用 draggable 在故事中创建贴纸。因为我可以有 1 个以上的贴纸,所以我将它们放在一个数组中,然后用一个按钮推动贴纸。 预期行为:当你移动贴纸(onDragRelease)时,我应该取贴纸的位置并在状态上更新它,但我不能取贴纸属性的绝对位置,因为在我释放拖动后,贴纸随机变化。我尝试使用 locationX、pageX(分别使用 Y)但仍然做同样的事情。
constructor(props) {
super(props);
const stickers = [];
const textStickers = [];
this.state = { textStickers };
this.state = { stickers };
}
当我按下添加按钮时(添加贴纸的功能):
let last = this.state.stickers.length;
this.setState(prevState => ({
stickers: [...prevState.stickers, {
id: last + 1,
uri: "https://cataas.com/cat/says/" + last + 1,
x: Dimensions.get('window').width / 2 - 75, //I put the new sticker on the center X
y: Dimensions.get('window').height / 2 - 75, //I put the new sticker on the center Y
size: 150
}]
}))
以及不起作用的位置函数:
onDragRelease={
(bounds) => {
this._changeFace
console.log("This sticker has id: " + sticker.id)
//Current sticker array
var array = this.state.stickers
//The new array
var newArray = []
//I use for to run the array and find the value I want to update (Based on ID)
for (let i = 0; i < array.length; i++) {
//If the ID is not the one on this sticker I just add it (push) with no changes
if (array[i].id !== sticker.id) {
newArray.push(array[i])
}
else //If this is the sticker, I edit the sticker on the array with i and just add it after editin
{
//First add it to the new array to avoid modifying the state without setState
newArray.push(array[i])
/*
! Now make the changes. Here you see I tried the solution of
! https://stackoverflow.com/questions/55529217/react-native-get-x-and-y-coordinates-of-draggable-object-using-panresponder-pan
! with no success, but also tried with only page, with only location and any single solution I thought could be the one.
*/
newArray[i].x = bounds.nativeEvent.pageX - bounds.nativeEvent.locationX //!BUG!
newArray[i].y = bounds.nativeEvent.pageY - bounds.nativeEvent.locationY //!BUG!
}
}
//Finally I update the changes putting newArray in the state
this.setState({
stickers: newArray
})
}
}
我希望每当我更新位置(拖动)时,我的状态中的位置都会发生变化,然后更新组件以使贴纸数组保持不变