React和requestAnimationFrame

时间:2018-10-24 18:03:17

标签: reactjs three.js components requestanimationframe

我目前正在玩React和Three.js。我正在尝试调用作为道具传递给另一个组件的更新函数,如下所示。问题是我收到一条错误消息,说this.cube未定义。

 public renderer : THREE.WebGLRenderer;
  public scene : THREE.Scene = new THREE.Scene();
  public camera : THREE.PerspectiveCamera = new THREE.PerspectiveCamera(70, 400 / 300, 0.1, 0.1);
  public cube : THREE.Mesh;

  public componentDidMount() {
    const geometry = new THREE.BoxGeometry( 1, 1, 1 );
    const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
    this.cube = new THREE.Mesh(geometry, material);
    this.scene.add(this.cube);
  }

     public update = () => {
        console.log(this);
        console.log(this.cube);
        this.cube.rotation.x += 0.01;
        this.cube.rotation.y += 0.01;
      }

      public render() {

        const sceneArr : THREE.Scene[] = [];
        sceneArr.push(this.scene);

        return (
          <React.Fragment>
            <Three mainCamera={this.camera} width={400} height={300} update={this.update} scenes={sceneArr} />
          </React.Fragment>
        );
      }

Here is the render function inside the `Three` component calling `requestAnimationFrame`.

      public threeRender = () => {
        this.props.update();
        requestAnimationFrame(this.threeRender);
        this.props.scenes.forEach(scene => {
          this.renderer.render(scene, this.props.mainCamera);
        });
      }

我假设thisupdate的上下文错误地引用了Three组件,但事实证明update内的print语句显示了相互矛盾的证据。

console.log(this)返回正确的对象上下文,并且多维数据集成员显示在日志中,但是console.log(this.cube)返回未定义。这对我来说毫无意义。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

constructor内初始化cube,然后应该能够引用它而不会出现该错误。

constructor(props){
   this.cube = {}
}

现在,您可以给this.cube赋予一个值,并从update()内引用它