我已经安装了 react-three-fiber 和 3 软件包。我正在关注this tutorial,但对于将这一行放在何处却有疑问:
const rootElement = document.getElementById("root");
此外,我开始收到此错误:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
我的index.js
:
import React, { Children, useRef, useState } from "react"
import { Link } from "gatsby"
import { Canvas} from 'react-three-fiber'
import Layout from "../components/layout"
const IndexPage = () => {
return(
<Layout>
<div>
<h1>Hi</h1>
</div>
<canvas>
<Children></Children>
</canvas>
</Layout>
)
}
const rootElement = document.getElementById("root");
export default IndexPage
有什么想法吗?
答案 0 :(得分:8)
确保同时安装了three
和react-three-fiber
。
npm install three react-three-fiber
然后在您的gatsby页面组件中,只需从Canvas
导入react-three-fiber
,然后再在JSX中使用它即可。
import React from "react"
import { Canvas} from 'react-three-fiber'
import Layout from "../components/layout"
const IndexPage = () => (
<Layout>
<Canvas />
</Layout>
)
export default IndexPage
关于const rootElement = document.getElementById("root");
:
尽管Gatsby
是由React
构建的,但它不需要您选择根元素即可呈现您的应用程序。如果这听起来令人困惑,则应该花一点时间来take a read of the Gatsby docs。
如果要从盖茨比的react-three-fiber docs来构建示例,它将看起来像这样。
import React, { useRef, useState } from "react"
import { Canvas, useFrame } from "react-three-fiber"
const Box = props => {
// This reference will give us direct access to the mesh so we can animate it
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 = mesh.current.rotation.y += 0.01))
return (
<mesh
{...props}
ref={mesh}
scale={active ? [1.5, 1.5, 1.5] : [1, 1, 1]}
onClick={e => setActive(!active)}
onPointerOver={e => setHover(true)}
onPointerOut={e => setHover(false)}
>
<boxBufferGeometry attach="geometry" args={[1, 1, 1]} />
<meshStandardMaterial
attach="material"
color={hovered ? "hotpink" : "orange"}
/>
</mesh>
)
}
const IndexPage = () => (
<Canvas>
<ambientLight />
<pointLight position={[10, 10, 10]} />
<Box position={[-1.2, 0, 0]} />
<Box position={[1.2, 0, 0]} />
</Canvas>
)
export default IndexPage