【问题标题】:React native: Set the coordinates for each item in arrayReact native:为数组中的每个项目设置坐标
【发布时间】:2021-10-02 16:40:20
【问题描述】:

我尝试获取每个 Draggaable 项目的坐标。
现在我得到了坐标,但我只得到了所有项目的一个值,但我想要每个项目的值。

这是我的数据

  const data = [
    {
      name: " ",
      X: 680,
      Y: 80,
      newposX: positionX,
      newposY: positionY,
    },
    {
      name: " ",
      X: 550 ,
      Y: 80,
      newposX: positionX,
      newposY: positionY,
    },
    {
      name: " ",
      X: 550 ,
      Y: 80,
      newposX: positionX,
      newposY: positionY,
    },
  ];

这里我打印出可拖动元素中的数据

            {data.map((item, key) => (
             <Draggable
                x={item.X}
                y={item.Y}
                renderColor="blue"
                renderSize={50}
                isCircle
                textcolor="#000000"
                renderText={item.name}
                onDragRelease={e => {
                  setPositionY(e.nativeEvent.pageY);
                  setPositionX(e.nativeEvent.pageX);
                }}
                />
              ))}

在“onDragRelease”上,我通过获取坐标来设置我的位置。但是在这里我也想为每个项目设置位置。但我不明白我的作品。有人知道我应该做什么吗?

【问题讨论】:

    标签: react-native coordinates draggable


    【解决方案1】:

    在您的data.map 函数中,您将item 的索引声明为变量key。您可以使用它来让新的setItemPosition 使用新位置更新您的数据数组。

    const setItemPosition = (key, x, y) => {
      const updatedData = [...data]
      const item = data[key];
      item.X = x
      item.Y = y
      const updatedData[key] = item
      
      setData(updatedData) // <-- This is your "setState" function for the data array.
    }
    
    // Use it in your draggable like this:
    
                {data.map((item, key) => (
                 <Draggable
                    x={item.X}
                    y={item.Y}
                    renderColor="blue"
                    renderSize={50}
                    isCircle
                    textcolor="#000000"
                    renderText={item.name}
                    onDragRelease={e => {
                      setItemPosition(key, e.nativeEvent.pageX, e.nativeEvent.pageY);
                    }}
                    />
                  ))}
    
    

    【讨论】:

    • 您好,感谢您的回答。它几乎可以工作了,它现在为每个项目设置了坐标,所以这很完美。但是可拖动项目以一种意想不到的方式移动,发生的是它从释放点移动了一些额外的坐标。在您的回答中,您两次添加了 updatedData 。在第二个声明中,我删除了 const 并添加了 updatedData [key] = item。但我不确定这是否正确?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    相关资源
    最近更新 更多