如何使用导入语法加载三轨道控件?

IT技术 javascript reactjs three.js
2021-05-04 15:25:41

有没有人试过在 ReactJS 中使用 OrbitControls 函数?这是我写的示例代码:

import React, { Component } from 'react';
import 'tachyons';
import * as THREE from 'react';
import OrbitControls from 'three-orbitcontrols';
class App extends Component {
render() {
...
//Controls
const controls = new OrbitControls(camera, renderer.domElement)
controls.dampingFactor = 0.25
controls.enableZoom = false

它返回以下错误:

./node_modules/three-orbitcontrols/OrbitControls.js
1054:70-89 "export 'OrbitControls' (imported as 'THREE') was not found in 'three'

有谁知道如何解决这个问题?

4个回答

还有一个选项可以直接从“三个”包中导入 OrbitControls,如下所示:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import * as THREE from 'three';
import {OrbitControls} from "three/examples/jsm/controls/OrbitControls";

并在应用程序中使用它没有任何问题:

this.controls = new OrbitControls(camera, domElement);

domElement必须在 Three.js 的最新版本中作为第二个参数传递。React ref 可以用于它。

这是一个带有最新 React 和 Three.js 的现场演示https://codesandbox.io/s/github/supromikali/react-three-demo

问题在于,当您导入 THREE 时,它不是全局范围的,而这正是“三轨道控制”module所依赖的。

您可以改用此module - 'three-orbit-controls'(https://www.npmjs.com/package/three-orbit-controls

并像这样导入它:

const OrbitControls = require('three-orbit-controls')(THREE);

轨道控制的使用与您现在使用的相同,但是这样,三个的实例被传递到轨道控制module。


编辑 - 2020

尽管在第一次提出问题时上述答案很有用,但@Marquizzo 正确地指出情况已不再如此。

Orbit Controls 现在与three.js 打包在一起require(),当您应该使用该import语句时,无需使用

请现在参考这个答案 - https://stackoverflow.com/a/55929101/8837901

我在使用包裹打包器时就是这样做的:

应用程序.js:

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

// the rest of the example from threejs web page 
// https://github.com/mrdoob/three.js/blob/master/examples/misc_controls_orbit.html

索引.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Parcel threejs example</title>
    <style>
      body {
        margin: 0;
      }
    </style>
  </head>
  <body>
    <script src="app.js"></script>
  </body>
</html>

包.json:

{
  "name": "test-threejs-with-parcel",
  "version": "0.1.0",
  "description": "Threejs with parcel test",
  "main": "app.js",
  "scripts": {
    "start": "parcel index.html",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "parcel-bundler": "^1.10.0"
  },
  "dependencies": {
    "three": "^0.109.0"
  }
}

您可以使用一个 npm 包:Orbit Controls ES6

链接:https : //www.npmjs.com/package/orbit-controls-es6

安装:

npm i orbit-controls-es6 --save

用法:

import OrbitControls from 'orbit-controls-es6';

const controls = new OrbitControls(camera, renderer.domElement);

2020 年更新:

three.js现在OrbitControls默认导出为module,正如其他人指出的那样,它可以按如下方式使用:

import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';