如何从react componentDidMount中的子方法调用父方法



我不能在react中使用componentDidMount之外的threejs方法。但我需要在这个组件(子(内部使用父方法,我需要它来对THRE.js对象执行操作。有没有办法在子函数的componentDidMount中获取和使用父方法?

我在家长版上试过

import logo from './logo.svg';
import './App.css';
import Canvas from './Canvas';
import * as THREE from 'three';
function App() {
function Hi (){
console.log("POOP");
}
return (
<div className="App">
<h1>this is the story of a man</h1>
<Canvas hi={Hi()}/>
</div>
);
}
export default App;

在孩子身上也是如此:

import './App.css';
import * as THREE from 'three';
import { GLTFLoader } from '../node_modules/three/examples/jsm/loaders/GLTFLoader';
export default class CanvAs extends React.Component{
constructor(props){
super(props)
}
componentDidMount(){
const hi = this.props;
var camera, scene, renderer, light;
var clock = new THREE.Clock();
var clock2 = new THREE.Clock();
let mixer;
let mixer2;
let player;
let Enemy;
let EnemyPositionZ;
let EnemyPositionX;
let playerPositionX;
let playerPositionZ;
var x = 0;
// var geometry, material, mesh;
init();
animate();
animate2();
//enemyAI();

function init() {
this.props.hi();
camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.z = 20;
camera.position.y = 1;
camera.scale.z = 10;
. . . 

有什么想法吗?:O

import React from "react";
class Canvas extends React.Component{
init(){
console.log("okay",this.props)
this.props.hi() //calling the hi function
}
render(){
console.log("props",this.props)
return(
<>
<div>i am the child comp</div>
</>
)
}
componentDidMount(){
console.log("in compdMount",this.props.hi)
this.init()
}
}
export default Canvas

在react类中,您不需要声明像函数init(({}这样的函数,只需声明init((或init=((=>即可。

最新更新