- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在阅读这个问题的最佳答案。
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.mount
。 this.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, theref
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/
我参加了一些类(class)并阅读了 YAGNI 的用途。但是,作为一个整体,这个原则从来没有让我满意。它引入了一个逻辑悖论。 作为一个假设,您正在设计一个打算向前扩展的框架。 YAGNI(可能还有
我是一名优秀的程序员,十分优秀!