我无法在componentDidMount
之外使用我的threejs方法来进行响应。但是我需要在该组件(子组件)中使用父方法,我需要它对THREE.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
答案 0 :(得分:2)
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 =()=> {} ,即可完成此操作 < / p>