daw*_*awn 3 three.js reactjs gatsby react-three-fiber
我已经安装了react-three-fiber和三个包。我正在关注本教程,但我怀疑将这一行放在哪里:
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
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
确保您已经安装了three和react-three-fiber。
npm install three react-three-fiber
Run Code Online (Sandbox Code Playgroud)
然后在你的 gatsby 页面组件中导入Canvasfromreact-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
Run Code Online (Sandbox Code Playgroud)
关于const rootElement = document.getElementById("root");:
尽管Gatsby是使用 构建的React,但它不需要您选择根元素来呈现您的应用程序。如果这听起来令人困惑,您应该花一点时间阅读 Gatsby 文档。
如果您要从Gatsby 中的react-three-fiber 文档构建示例,它看起来像这样。
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2165 次 |
| 最近记录: |