React类组件中如何在一个方法内调用另一个方法?
解决React类组件中onSceneReady无法访问state/方法的问题
问题核心是onSceneReady方法执行时,this的上下文没有绑定到组件实例,导致无法访问组件的state、props和自定义方法。下面是几种直接可行的解决方案:
方案1:在构造函数中手动绑定this
在组件的constructor里,给目标方法绑定组件实例的this:
constructor(props) { super(props); this.state = { face: 2 }; // 绑定onSceneReady的this指向 this.onSceneReady = this.onSceneReady.bind(this); // 也可以同时绑定res方法,避免后续调用时出现同样问题 this.res = this.res.bind(this); }
方案2:用箭头函数定义类方法
箭头函数会自动继承当前上下文的this,直接把类方法改成箭头函数形式即可:
constructor(props) { super(props); this.state = { face: 2 }; } // 箭头函数定义res方法 res = (meshes) => { return meshes.findIndex((e) => e.name === 'front'); } componentDidUpdate() { console.log(this.state.face); //2 } // 箭头函数定义onSceneReady方法 onSceneReady = (scene) => { // 注意:原代码中直接使用meshes变量可能是笔误,需从scene中获取,比如scene.meshes const meshes = scene.meshes; modelMesh = meshes[this.res(meshes)]; modelMesh = meshes[this.state.face]; }
方案3:调用时用箭头函数包裹
如果onSceneReady是作为回调传递给第三方组件或库,在传递时用箭头函数包裹,确保this指向组件实例:
render() { return ( <ThirdPartyComponent onSceneReady={(scene) => this.onSceneReady(scene)} /> ); }
另外注意:原代码中onSceneReady的参数是scene,但直接使用meshes变量属于未定义状态,需从scene对象中获取对应属性(比如scene.meshes),否则会触发新的报错。
内容的提问来源于stack exchange,提问作者user21347334
相关产品推荐
相关产品推荐

