【问题标题】:How to organize imports in a React App with three.js (without using the window object)?如何使用 three.js(不使用 window 对象)在 React App 中组织导入?
【发布时间】:2018-09-02 06:28:25
【问题描述】:

问题:

假设我想创建一个 React 应用,左侧是 3D 组件,右侧是其他一些 UI 组件。

3D 的东西是用 three.js 完成的,假设我想克隆这个 3D 应用程序:https://threejs.org/examples/?q=edit#webgl_geometry_spline_editor

目前,我在 index.html 中包含 3D 应用程序所需的脚本,如下所示:

<script src="../build/three.js"></script>
<script src="js/controls/DragControls.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script src="js/controls/TransformControls.js"></script>
<script src="js/libs/stats.min.js"></script>
<script src="js/libs/dat.gui.min.js"></script>

(为简洁起见,省略 %PUBLIC_URL%)。

现在在我的 React 3DComponent 中,我可以通过使用全局窗口对象来使用这些脚本中的对象和方法,如下所示:

controls = new window.THREE.OrbitControls(camera, renderer.domElement);
var clock = new window.THREE.Clock();

问题:

  1. 是否有更优雅的方式来导入这些脚本,这样我就不必将脚本导入到全局空间?我可以将 three.js 作为模块导入,但其他一些脚本(DragControls、OrbitControls)需要主 Three.js 文件中的对象,因此我必须将其保存在全局空间中。

  2. 有没有办法通过省略对全局窗口对象的调用来缩短这些调用?如果没有这个,我可以复制和粘贴 3d 场景的示例代码,而无需调用“.window”。在每个方法和对象调用之前。

很抱歉,如果这些问题有点令人讨厌,但我是 React 和 Three.js 的新手。

【问题讨论】:

    标签: javascript reactjs three.js create-react-app


    【解决方案1】:

    创建three.js 文件并粘贴以下代码。

    const THREE = require("three");
    global.THREE = THREE;
    if (!window.addEventListener) window.addEventListener = () => {};
    require("three/examples/js/controls/DragControls.js");
    require("three/examples/js/controls/OrbitControls.js");
    require("three/examples/js/controls/TransformControls.js");
    require("three/examples/js/libs/stats.min.js");
    require("three/examples/js/libs/dat.gui.min.js");
    export default THREE;
    

    将此文件导入您的任何组件中。

    import THREE from "./three";
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-02-25
      • 2017-09-24
      • 2014-05-18
      • 1970-01-01
      • 2014-12-25
      • 2020-12-17
      • 2021-06-09
      • 2021-07-23
      • 1970-01-01
      相关资源
      最近更新 更多