对于使用 React-Three-Fiber 制作的项目,我导入了以下库:
import * as THREE from 'three';
import React, { Suspense, useState } from "react";
import { Canvas, useLoader } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
效果很好,然后我决定为场景制作一个更整洁的 UI,并尝试根据
https://sbcode.net/thirdjs/dat-gui/导入
import { GUI } from '/jsm/libs/dat.gui.module';
但是显示错误:
Failed to compile
./src/App.js
Module not found: You attempted to import /jsm/libs/dat.gui.module which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
This error occurred during the build time and cannot be dismissed.
这很奇怪,因为之前的四个库都在 src 之外。
然后我尝试输入相对路径,但编译器无法解析该路径。
然后我尝试将 dat.gui.module.js 文件移动到 src 文件夹内,但出现了相同的“无法解析”错误。
这是我的项目的文件夹结构:
-Project
|-node_modules
| L-(all the ext. libs including @react-three etc.)
|-src
| L-App.js
L-public
L-index.html
如何让 dat.gui 在我的 React-三纤维项目中工作?
您必须像
import { GUI } from 'three/examples/jsm/libs/dat.gui.module'
一样导入它。然后你就可以在useEffect
内部使用它,如下例所示。
const gui = new GUI()
useEffect(() => {
const folder = gui.addFolder("Light")
folder.add(lightRef.current, 'intensity', 0, 1, 0.001)
}, [])
您需要使用动态导入而不是静态导入将 dat.gui 导入到react.js中。
而不是这个:
import { GUI } from 'three/examples/jsm/libs/dat.gui.module'
在
componentDidMount
或 useEffect
钩子内尝试一下:
const { GUI } = await import('three/examples/jsm/libs/dat.gui.module')
const gui = new GUI()
或者这个:
import('three/examples/jsm/libs/dat.gui.module').then(({ GUI }) => {
const gui = new GUI()
})
我创建了一个专门用于在 React Three Fiber 中使用
Dat.GUI
的页面
https://sbcode.net/react- Three-Fiber/dat.gui/
Dat.GUI 不是为 React 编写的,因此您确实需要考虑在重新渲染 JSX 时进行清理。
useEffect(() => {
const gui = new GUI()
gui.add(someObject, 'somePropertyy', minValue, maxValue)
return () => {
gui.destroy()
}
}, [])
无论如何,一些例子,因为我发现使用例子更容易解释。
https://editor.sbcode.net/348ef2f2a58cab80e23ef038b4f93df408f68aa3
https://editor.sbcode.net/ea1c7654a7a943593b0e250af5b68602645ed20d
https://editor.sbcode.net/35094a3db3ace7db06731a7c540a7d2db45d0dfa