gpt4 book ai didi

reactjs - 引用回调和 this.mount -reactJS

转载 作者:行者123 更新时间:2023-12-02 15:32:27 25 4
gpt4 key购买 nike

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

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) => { this.mount = mount }} 在做什么?

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

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

最佳答案

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

When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument.

所以在:

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

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

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

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

关于reactjs - 引用回调和 this.mount -reactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49469961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com