参考回调& this.mount - reactJS

时间:2018-03-24 21:06:29

标签: reactjs three.js

我正在阅读这个问题的最佳答案。

How to connect Threejs to React?

有人提供了使用threejs作为反应的一个很好的例子:

import React, { Component } from 'react'
import * as THREE from 'three'

class Scene extends Component {
constructor(props) {
super(props)

this.start = this.start.bind(this)
this.stop = this.stop.bind(this)
this.animate = this.animate.bind(this)
}

componentDidMount() {
const width = this.mount.clientWidth
const height = this.mount.clientHeight

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(
  75,
  width / height,
  0.1,
  1000
)
const renderer = new THREE.WebGLRenderer({ antialias: true })
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: '#433F81' })
const cube = new THREE.Mesh(geometry, material)

camera.position.z = 4
scene.add(cube)
renderer.setClearColor('#000000')
renderer.setSize(width, height)

this.scene = scene
this.camera = camera
this.renderer = renderer
this.material = material
this.cube = cube

this.mount.appendChild(this.renderer.domElement)
this.start()
}

componentWillUnmount() {
this.stop()
this.mount.removeChild(this.renderer.domElement)
}

start() {
if (!this.frameId) {
  this.frameId = requestAnimationFrame(this.animate)
}
}

stop() {
  cancelAnimationFrame(this.frameId)
}

animate() {
this.cube.rotation.x += 0.01
this.cube.rotation.y += 0.01

this.renderScene()
this.frameId = window.requestAnimationFrame(this.animate)
}

renderScene() {
  this.renderer.render(this.scene, this.camera)
}

render() {
return (
  <div
    style={{ width: '400px', height: '400px' }}
    ref={(mount) => { this.mount = mount }}
  />
)
}
}

export default Scene

我不明白this.mount。什么是this.mount?它似乎用于访问客户端宽度和客户端高度。什么是ref回调函数ref={(mount) => { this.mount = mount }}在做什么?

我做了一些研究,发现在组件安装后会调用ref回调,它们可以用于将状态从父项传递给子项,但只能在必要时使用它们。我从文档中得到了所有这些。

我打算为了自己的目的修改这个脚本,所以理解this.mount和ref回调会非常有用。 TIA

1 个答案:

答案 0 :(得分:3)

检查文档 - React Refs and the DOM(强调我的):

  

在HTML元素上使用ref属性时,ref回调会将基础DOM元素作为其参数

所以:

  render() {
    return (
      <div
        style={{ width: '400px', height: '400px' }}
        ref={(mount) => { this.mount = mount }}
      />
    )
  }

this.mount将保留对安装组件的实际<div> 的引用。

重要的是要注意this.mount仅在安装组件后才存在。这就是为什么使用this.mount is in componentDidMount()或之后的所有逻辑,只有在安装组件后才会触发:

  安装组件后立即调用

componentDidMount() 。需要DOM节点的初始化应该放在这里。如果需要从远程端点加载数据,这是实例化网络请求的好地方。