【问题标题】:Ref callbacks & this.mount - reactJS参考回调和 this.mount - reactJS
【发布时间】:2018-09-03 07:53:29
【问题描述】:

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

How to connect Threejs to React?

有人提供了这个在 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.mountthis.mount 是什么?它似乎用于访问客户端宽度和客户端高度。而 ref 回调函数ref={(mount) =&gt; { this.mount = mount }} 是干什么的?

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

我计划出于自己的目的修改此脚本,因此了解 this.mount 和 ref 回调将非常有帮助。 TIA

【问题讨论】:

    标签: reactjs three.js


    【解决方案1】:

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

    当在 HTML 元素上使用 ref 属性时,ref 回调接收底层 DOM 元素作为其参数

    所以在:

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

    this.mount 将持有对组件安装到的实际&lt;div&gt; 的引用。

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

    componentDidMount() 在组件安装后立即调用。需要 DOM 节点的初始化应该放在这里。如果您需要从远程端点加载数据,这是一个实例化网络请求的好地方。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多