我正在使用React和ThreeJS将3D模型导入到网页中。问题出在将网格物体加载到ThreeJS场景的函数中。我收到以下错误:
TypeError: Cannot read property 'scene' of undefined
就在这行之前,我将网格添加到场景中,然后打印出相同的对象,并且GLB文件中有一个“场景”属性。这是一张图片:
这是我的代码:
import React, { Component } from 'react'
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import gltfPath from '/home/mateus/Documents/index/src/cube.glb'
class ThreeDViewer extends Component {
componentDidMount() {
const width = this.mount.clientWidth
const height = this.mount.clientHeight
this.scene = new THREE.Scene()
this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 5000)
this.camera.position.z = 20
this.renderer = new THREE.WebGLRenderer()
this.renderer.setSize(width, height)
this.mount.appendChild(this.renderer.domElement)
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: '#00ff00' })
this.cube = new THREE.Mesh(geometry, material)
this.light = new THREE.AmbientLight(0xffffff, 100)
this.scene.add(this.light)
this.loader = new GLTFLoader()
this.loader.load(gltfPath, function (gltf) {
// I print gltf but I can't add it to my scene I don't know why
console.log(gltf)
this.scene.add(gltf.scene.children[2])
}, undefined, function (error) {
console.error(error)
})
this.start()
}
如果我从ThreeJs lib添加多维数据集,则可以正常工作,但对于我的自定义模型,则无法正常工作。模型只是搅拌器2.81导出为glb的简单多维数据集。
答案 0 :(得分:2)
this
在回调中未定义,请尝试使用箭头函数代替函数声明:
this.loader.load(gltfPath, (gltf) => {
this.scene.add(gltf.scene.children[2]);
});