【问题标题】:Can't get react-three/fiber to render a canvas in my react-native project无法在我的 react-native 项目中获得 react-three/fiber 来渲染画布
【发布时间】:2021-11-27 19:03:10
【问题描述】:

我有一些应用程序有一些包含多个页面的代码。在一页上,我想要一个three 画布。

我有一些这样的代码。

export const MyScreen = ({navigation}) => {
   return (
     <View>
       <SomeHeader navigator={navigation}/>
       <View style={styles.canvas}>
         <MyCanvas/>
       </View>
     </View>
 );

那我也有这段代码。

export class MyCanvas extends React.Component {

  render() {
    // This reference will give us direct access to the mesh
    const mesh = useRef()
    // Set up state for the hovered and active state
    const [hovered, setHover] = useState(false)
    const [active, setActive] = useState(false)
    // Rotate mesh every frame, this is outside of React without overhead
    useFrame(() => (mesh.current.rotation.x += 0.01))

    return (
        <Canvas>
          <mesh
            {...props}
            ref={mesh}
            scale={active ? 1.5 : 1}
            onClick={(event) => setActive(!active)}
            onPointerOver={(event) => setHover(true)}
            onPointerOut={(event) => setHover(false)}>
            <boxGeometry args={[1, 2, 3]} />
            <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
          </mesh>
        </Canvas>
    );
  }
}

导致此错误

未捕获的错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一:

钩子不是在函数组件的主体中吗?我很困惑。

【问题讨论】:

    标签: reactjs react-native three.js


    【解决方案1】:

    MyCanvas 是一个类组件,因为它扩展了React.Component

    在你的情况下,我猜你想要的是这样的:

    function MyCanvas() {
      const mesh = useRef()
      const [hovered, setHover] = useState(false)
      const [active, setActive] = useState(false)
      useFrame(() => (mesh.current.rotation.x += 0.01))
    
      return (
        <Canvas>
          <mesh
            {...props}
            ref={mesh}
            scale={active ? 1.5 : 1}
            onClick={(event) => setActive(!active)}
            onPointerOver={(event) => setHover(true)}
            onPointerOut={(event) => setHover(false)}>
            <boxGeometry args={[1, 2, 3]} />
            <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
          </mesh>
        </Canvas>
      );
    }
    

    React 文档有更多关于相同错误的详细信息。 https://reactjs.org/warnings/invalid-hook-call-warning.html

    不过,上述错误与 r3f 无关。但是 r3f 可能不适用于 React Native。 Github repo 上有一些问题,我最初的研究计划为第 8 版发布一个开放 PR https://github.com/pmndrs/react-three-fiber/pull/1384

    https://github.com/pmndrs/react-three-fiber/pull/1699

    【讨论】:

    • 不幸的是,这并不能解决我的问题,因为我得到“未捕获的 R3F 挂钩只能在 Canvas 组件中使用!” (我最初尝试过这个,但改变了我在问题中发布的内容)。你带来了一个很好的观点,尽管它似乎没有得到官方的支持。我可能会研究其他一些库来做出原生反应
    猜你喜欢
    • 2022-01-04
    • 2021-07-15
    • 2020-08-13
    • 2020-10-31
    • 2021-10-02
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    相关资源
    最近更新 更多