Javascript 使用React类在Three.js中分离文件
我已经构建了一个three.js应用程序,但我正在努力弄清楚如何将我的函数放在不同的文件中 我得到了这个网格函数,我想在它自己的单独文件中Javascript 使用React类在Three.js中分离文件,javascript,reactjs,three.js,Javascript,Reactjs,Three.js,我已经构建了一个three.js应用程序,但我正在努力弄清楚如何将我的函数放在不同的文件中 我得到了这个网格函数,我想在它自己的单独文件中 addCustomSceneObjects = () => { const geometry = new THREE.BoxGeometry(2, 2, 2); const material = new THREE.MeshPhongMaterial({color: 0x156289, emissive: 0x072534, sid
addCustomSceneObjects = () => {
const geometry = new THREE.BoxGeometry(2, 2, 2);
const material = new THREE.MeshPhongMaterial({color: 0x156289, emissive: 0x072534, side: THREE.DoubleSide, flatShading: true});
this.cube = new THREE.Mesh(geometry, material);
this.scene.add(this.cube);
}
我的功能
componentDidMount() {
this.sceneSetup();
this.addCustomSceneObjects();
this.startAnimationLoop();
window.addEventListener("resize", this.handleWindowResize);
}
我的场景功能
sceneSetup = () => {
const width = this.el.clientWidth;
const height = this.el.clientHeight;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
this.camera.position.z = 5;
this.controls = new OrbitControls(this.camera, this.el);
this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize(width, height);
this.el.appendChild(this.renderer.domElement); // mount using React ref
};
我的网格函数这是我希望在单独的文件中包含的函数
addCustomSceneObjects = () => {
const geometry = new THREE.BoxGeometry(2, 2, 2);
const material = new THREE.MeshPhongMaterial({color: 0x156289, emissive: 0x072534, side: THREE.DoubleSide, flatShading: true});
this.cube = new THREE.Mesh(geometry, material);
this.scene.add(this.cube);
}
非常感谢您对我的建议。我从未使用过three.js,但您的需求不是特定于框架的
// addCustomSceneObjects.js
export default ({ scene, cube}) => {
const geometry = new THREE.BoxGeometry(2, 2, 2);
const material = new THREE.MeshPhongMaterial({color: 0x156289, emissive:
0x072534, side: THREE.DoubleSide, flatShading: true});
cube = new THREE.Mesh(geometry, material);
scene.add(this.cube);
}
然后,像这样使用提取的函数
// index.jsx
import addCustomSceneObjects from './addCustomSceneObjects'
componentDidMount() {
//...
addCustomSceneObjects({ scene: this.scene, cube: this.cube })
}
这给了我以下错误:TypeError:无法读取未定义的属性“cube”。我已经尝试了几个小时不同的解决方案,但似乎无法运行它。你还有什么建议吗?我有办法了!在addCustomSceneObjects上忘记了“this”