three.jsでシーンを構築するために、 react-three-renderer ( npm、github ) を使用しています。
私はMVCEに要約したという問題を抱えています。参照が期待どおりに更新されていません。まず、主なコードは次のとおりです。
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
. 私が遭遇している問題の核心はここにあります。トグル ボタンを初めてクリックした後、形状の参照が円を指していると思います。しかし、ログからわかるようにcomponentDidUpdate
、ref ではまだボックスを指しています。
componentDidUpdate: アクティブな形状はボックスです
その後の行にログインすると、ref コールバックがヒットしたことがわかります
box ref null [React はメモリ リークを防ぐために古い ref で null を呼び出します]
circle ref [オブジェクト オブジェクト]
ブレークポイントをドロップして、検証および検査することができます。に入る前に、これら 2 つのことが起こるcomponentDidUpdate
と思いますが、ご覧のとおり、逆に起こっています。どうしてこれなの?react-three-renderer に根本的な問題がありますか (もしそうなら、診断できますか?)、または React 参照を誤解していますか?
MVCE は、この github リポジトリで入手できます。ダウンロードして実行しnpm install
、_dev/public/home.html を開きます。
前もって感謝します。