我正在阅读此问题的最佳答案。
如何将三j连接到反应?
有人提供了在React中使用三j的很好的例子:
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={(mount) => { this.mount = mount }}
是什么?
我进行了一些研究,发现在组件坐骑后调用了参考回调,可用于从父母到孩子的状态,但仅应在必要时使用它们。我从文档那里得到了所有这些。
我计划为自己的目的修改此脚本,因此了解this.mount
和Ref回调确实很有帮助。tia
检查文档 - react refs和dom(强调矿山(:
当在HTML元素上使用
ref
属性时,ref
回调接收基础DOM元素作为其参数。
so in:
render() {
return (
<div
style={{ width: '400px', height: '400px' }}
ref={(mount) => { this.mount = mount }}
/>
)
}
this.mount
将保存对实际<div>
将组件安装到。
重要的是要注意this.mount
仅在安装组件之后仅存在。这就是为什么所有使用this.mount
的逻辑都在componentDidMount()
或之后的原因,仅在安装组件后才触发:
componentDidMount()
在安装组件后立即调用。需要DOM节点的初始化应该在此处。如果您需要从远程端点加载数据,这是实例化网络请求的好地方。