我正在使用 react-three-renderer ( npm , github ) 来构建一个带有three.js的场景。
我遇到了一个归结为 MVCE 的问题。Refs 没有按照我期望的顺序更新。首先,这是要查看的主要代码:
var React = require('react');
var React3 = require('react-three-renderer');
var THREE = require('three');
var ReactDOM = require('react-dom');
class Simple extends React.Component {
constructor(props, context) {
super(props, context);
// construct the position vector here, because if we use 'new' within render,
// React will think that things have changed when they have not.
this.cameraPosition = new THREE.Vector3(0, 0, 5);
this.state = {
shape: 'box'
};
this.toggleShape = this.toggleShape.bind(this);
}
toggleShape() {
if(this.state.shape === 'box') {
this.setState({ shape: 'circle' });
} else {
this.setState({ shape: 'box' });
}
}
renderShape() {
if(this.state.shape === 'box') {
return <mesh>
<boxGeometry
width={1}
height={1}
depth={1}
name='box'
ref={
(shape) => {
this.shape = shape;
console.log('box ref ' + shape);
}
}
/>
<meshBasicMaterial
color={0x00ff00}
/>
</mesh>;
} else {
return <mesh>
<circleGeometry
radius={2}
segments={50}
name='circle'
ref={
(shape) => {
this.shape = shape;
console.log('circle ref ' + shape);
}
}
/>
<meshBasicMaterial
color={0x0000ff}
/>
</mesh>
}
}
componentDidUpdate() {
console.log('componentDidUpdate: the active shape is ' + this.shape.name);
}
render() {
const width = window.innerWidth; // canvas width
const height = window.innerHeight; // canvas height
var position = new THREE.Vector3(0, 0, 10);
var scale = new THREE.Vector3(100,50,1);
var shape = this.renderShape();
return (<div>
<button onClick={this.toggleShape}>Toggle Shape</button>
<React3
mainCamera="camera"
width={width}
height={height}
onAnimate={this._onAnimate}>
<scene>
<perspectiveCamera
name="camera"
fov={75}
aspect={width / height}
near={0.1}
far={1000}
position={this.cameraPosition}/>
{shape}
</scene>
</React3>
</div>);
}
}
ReactDOM.render(<Simple/>, document.querySelector('.root-anchor'));
这会渲染一个带有绿色框的基本场景,这是 react-three-renderer 的 github 登录页面上示例的一个分支。左上角的按钮将场景中的形状切换为蓝色圆圈,如果再次单击,则返回绿色框。我在 ref 回调和componentDidUpdate
. 这就是我遇到的问题的核心所在。第一次单击切换按钮后,我希望形状的 ref 指向圆。但正如您从日志中看到的那样,在componentDidUpdate
ref 中仍然指向该框:
componentDidUpdate:活动形状是框
之后登录行显示 ref 回调被命中
box ref null [React 在旧 ref 上调用 null 以防止内存泄漏]
圆参考 [object 对象]
您可以放入断点以进行验证和检查。我预计这两件事会在我们进入之前发生componentDidUpdate
,但正如你所看到的,它正在反过来发生。为什么是这样?react-three-renderer 中是否存在潜在问题(如果有,您可以诊断它吗?),还是我误解了 React refs?
MVCE 在这个 github 存储库中可用。下载它,运行npm install
,然后打开 _dev/public/home.html。
提前致谢。