如何将JS编写的Three.js组件导入React TypeScript项目的App.tsx中使用
操作步骤
1. 修复ThreeScene.js的错误代码
你当前的ThreeScene.js中包含冗余的全局渲染逻辑,导入后会导致重复挂载报错,先修改为如下代码:
import React from "react"; import * as THREE from "three"; // React组件名必须大驼峰命名,否则会被识别为原生HTML标签 class MyBox extends React.Component { // 存储动画帧ID,用于卸载时清理 animationId = null; renderer = null; componentDidMount() { const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); this.renderer = new THREE.WebGLRenderer(); this.renderer.setSize(window.innerWidth, window.innerHeight); this.mount.appendChild(this.renderer.domElement); const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshStandardMaterial({ color: 0x7e31eb }); const cube = new THREE.Mesh(geometry, material); scene.add(cube); const light = new THREE.HemisphereLight(0xffffbb, 0x080820, 1); scene.add(light); camera.position.z = 2; const animate = () => { this.animationId = requestAnimationFrame(animate); cube.rotation.x += 0.01; cube.rotation.y += 0.01; cube.rotation.z += 0.01; this.renderer.render(scene, camera); }; animate(); } // 组件卸载时清理资源,避免内存泄漏 componentWillUnmount() { cancelAnimationFrame(this.animationId); this.renderer.dispose(); this.mount.removeChild(this.renderer.domElement); } render() { return ( <div ref={ref => (this.mount = ref)} /> ) } } export default MyBox;
- 核心修改点:删除了原代码末尾直接调用
ReactDOM.render(<myBox />, rootElement)的全局渲染逻辑,补充了组件卸载时的资源清理逻辑,修正了组件命名规范。
2. 安装项目依赖
在项目根目录执行命令安装three相关依赖和TS类型声明包:
npm install three @types/three # 如果你用yarn就执行 # yarn add three @types/three
3. TypeScript配置适配
打开项目根目录的tsconfig.json文件,确保compilerOptions下添加/修改allowJs配置为true,允许TS项目导入JS文件:
{ "compilerOptions": { "allowJs": true, // 其他原有配置保持不变 } }
如果不想全局开启allowJs,也可以直接把ThreeScene.js重命名为ThreeScene.tsx,补充简单的类型声明即可。
4. 在App.tsx中引入使用组件
打开你的App.tsx文件,按如下方式引入使用即可:
import React from 'react'; // 按你实际的文件路径调整导入路径 import MyBox from './ThreeScene'; function App() { return ( <div className="App"> {/* 其他原有页面内容 */} <MyBox /> </div> ); } export default App;
内容的提问来源于stack exchange,提问作者QS123
相关产品推荐
相关产品推荐

