React-360中Three.js场景无法渲染,咨询对应渲染组件
解决React 360中Three.js场景无法渲染的问题
我来帮你梳理下代码里的核心问题,一步步修正后就能让你的立方体正常显示了:
问题分析
- 模块调用时机错误:你在
CubeModule的constructor里直接调用Cube123.add(),此时React 360的场景还没完成初始化,导致Mesh没能被正确挂载到活跃场景中。 - 灯光配置缺失:虽然你用的
MeshBasicMaterial不受灯光影响,但React 360的默认场景需要明确的灯光配置才能稳定渲染3D内容,而且后续切换材质也会依赖灯光。 - 场景挂载逻辑冗余:你手动给
r360.scene = scene,但创建ReactInstance时已经传入了scene参数,这一步不仅多余,还可能导致场景挂载冲突。 - 3D位置可见性问题:立方体位置设为
mesh.position.z = -4,但renderToLocation用的Location([0, -2, -10])可能让相机视角没对准立方体,导致看不到。
修正后的代码实现
1. 调整Cube模块(Cube.js)
简化逻辑,明确方法命名:
import { Module } from 'react-360-web'; import * as THREE from 'three'; export default class Cube extends Module { constructor(scene) { super('Cube123'); this.scene = scene; } addCube() { const geometry = new THREE.BoxGeometry(100, 100, 100); const material = new THREE.MeshBasicMaterial({ color: Math.random() * 0xffffff }); const mesh = new THREE.Mesh(geometry, material); // 调整到相机可见的核心位置 mesh.position.set(0, 0, -5); this.scene.add(mesh); } }
2. 修正client.js初始化逻辑
确保场景正确传递,添加必要灯光:
import { ReactInstance, Surface } from 'react-360-web'; import Cube from './Cube'; import * as THREE from 'three'; function init(bundle, parent, options = {}) { const scene = new THREE.Scene(); // 添加基础灯光,保证3D内容渲染稳定性 const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); scene.add(ambientLight); const pointLight = new THREE.PointLight(0xffffff, 1); pointLight.position.set(5, 5, -10); scene.add(pointLight); const cubeModule = new Cube(scene); const r360 = new ReactInstance(bundle, parent, { fullScreen: true, nativeModules: [cubeModule], scene: scene, ...options, }); // 创建平面Surface渲染2D组件,同时3D立方体会直接渲染在场景中 const mainSurface = new Surface(800, 600, Surface.SurfaceShape.Flat); mainSurface.setAngle(0, 0); r360.renderToLocation( r360.createRoot('CubeModule123'), mainSurface ); r360.compositor.setBackground('./static_assets/360_world.jpg'); } window.React360 = { init };
3. 修正CubeModule组件生命周期
把添加立方体的操作延后到组件挂载完成后:
import * as React from 'react'; import { Animated, View, NativeModules } from 'react-360'; const Cube123 = NativeModules.Cube123; export default class CubeModule extends React.Component { componentDidMount() { // 组件挂载完成后再调用添加方法,此时场景已完全初始化 Cube123.addCube(); } render() { return ( <Animated.View style={{ height: 100, width: 200, transform: [{ translate: [0, 0, -3] }], backgroundColor: 'rgba(255, 255, 255, 0.4)', layoutOrigin: [0.5, 0], alignItems: 'center', }} > {/* 可添加文本确认组件是否正常渲染 */} {/* <Text>Three.js 立方体测试</Text> */} </Animated.View> ); } }
关键说明
- Three.js场景的渲染逻辑:在React 360中,你不需要找特定组件来渲染Three.js场景——只要把Three.js的Mesh添加到
ReactInstance初始化时传入的scene中,它就会和React 360的内容一起渲染。 - 生命周期时机:永远不要在组件
constructor中调用场景操作方法,改用componentDidMount(类组件)或useEffect(函数组件),确保底层渲染环境准备完毕。 - 可见性检查:React 360默认相机位置是
(0,0,0)、朝向z轴负方向,所以把Mesh放在z=-5左右的位置能确保在视锥体内。
内容的提问来源于stack exchange,提问作者Vineet Hariharan
相关产品推荐
相关产品推荐

