【问题标题】:How to get the id of an object in react-three-fiber如何在react-three-fiber中获取对象的ID
【发布时间】:2021-12-29 16:37:20
【问题描述】:

我正在尝试获取我在react-three-fiber 中创建的对象的id。我尝试使用document.getElementById,但没有成功。

这是我创建的对象:

 const createFace = () => {
    let face = [];
    let size = props.cubeArr[0].length;
    for (let row = 0; row < size; row++) {
      let rowArr = [];
      for (let col = 0; col < size; col++) {
        let position = [col - 1, size - 2 - row, 0];
        rowArr[col] = (
          <Cell
            key={`${props.side}-${row}-${col}`}
            id={`${props.side}-${row}-${col}`}
            position={position}
          />
        );
      }
      face[row] = <group key={`${props.side}-${row}`}>{rowArr}</group>;

为简洁起见,我没有包含其余的three.js 代码,但基本上我为我的每个Cells 设置了一个id,我想根据他们的ID 访问这些3D Cells,所以我可以运行click 函数。

我发现了一个类似的问题here,但看不到如何翻译它以做出反应

【问题讨论】:

    标签: javascript three.js react-three-fiber


    【解决方案1】:

    三个.js 对象有这个可选的property called .name。您可以为您的网格分配名称,然后您可以使用.getObjectByName() 访问它们。这是一个干净的替代方案,可以让您摆脱 React 的草率 useRef 方法:

    // First you assign a name to the object
    const mesh = new THREE.Mesh(geometry, material);
    mesh.name = "mySpecialMesh";
    
    // ...
    
    // Then later on you can find this object by the name you assigned
    const sameMesh = scene.getObjectByName("mySpecialMesh");
    

    我认为你可以用&lt;Cell name="mySpecialMesh" /&gt;做类似的事情

    【讨论】:

      【解决方案2】:

      发布此消息后不久,我找到了一些关于在我的群组中使用 useRef 挂钩的答案。

      此实现有效,但不确定它是否是最合适的方法。无论如何,到目前为止,这种方法有效

      import React, {useRef} from 'react'
      
      const Cell = (props) => {
      
         let cellRef = useRef();
      
         const clickSurroundingCell = (e) => {
            e.stopPropagation()
            let cubeObject = cellRef.current.parent.parent.parent // get main parent to check all objects
            // clicking on the cell reference here
            let cellToClick = cubeObject.children[0].children[0].children[0] 
            cellToClick.__r3f.handlers.onClick(event) // this executes the referenced cell onClick function
        }
      
        return (
            <Plane onClick={clickSurroundingCell}>
            </Plane>
        )
      }
      

      【讨论】:

        猜你喜欢
        • 2021-03-09
        • 2021-10-18
        • 2020-10-31
        • 2020-10-09
        • 2022-01-04
        • 1970-01-01
        • 2022-06-21
        • 2021-08-20
        • 2019-10-27
        相关资源
        最近更新 更多