我需要添加控件来操作在useEffect中声明的rubiks对象。控件是一系列按钮,需要调用多维数据集类(rubiks属于该类(中内置的函数,这些函数存在于名为"ControlBar"的单独组件中。我尝试使用useRef并声明上面的对象useEffect,但当我试图用"将rubiks对象的引用传递给ControlBar时,我遇到了一个错误;ref={rubiks}";。我也尝试过使用道具,但也没有成功。感谢您的任何帮助。非常感谢。
CubeContainer组件:
const CubeContainer = () => {
useEffect(() => {
const playground = document.getElementById('playground');
const scene = new THREE.Scene();
//@ts-ignore
const camera = new THREE.PerspectiveCamera( 75, playground?.offsetWidth / playground?.offsetHeight, 0.1, 1000 );
camera.position.set(5,5,5);
const renderer = new THREE.WebGLRenderer();
// @ts-ignore
renderer.setSize( playground?.offsetWidth, playground?.offsetHeight );
playground?.appendChild( renderer.domElement );
const light = new THREE.HemisphereLight( 0xffffff, 0xababab, 1 );
scene.add(light);
let rubiks = new Cube(scene);
rubiks.build();
const fullCube = rubiks.getParentObj();
scene.add(fullCube);
//@ts-ignore
const controls = new OrbitControls(camera, playground);
// camera.worldToLocal(fullCube.position)
const axesHelper = new THREE.AxesHelper( 1 );
scene.add( axesHelper );
function animate() {
requestAnimationFrame( animate );
controls.update()
renderer.render( scene, camera );
}
animate();
});
return (
<>
<div className="col-span-5 row-span-5 playarea">
<div id="playground" className="h-full"></div>
</div>
<MoveBar />
<ControlBar /> <
</>
);
}
export default CubeContainer;
控制条组件:
const ControlBar = () => {
return (
<div className="col-span-7 bg-zinc-800">
<div className="col-span-5 text-center inline-block">
<div className="float-left">
<FButton/>
<F_Button/>
</div>
<div className="float-left">
<RButton/>
<R_Button/>
</div>
<div className="float-left">
<UButton/>
<U_Button/>
</div>
<div className="float-left">
<DButton/>
<D_Button/>
</div>
<div className="float-left">
<LButton/>
<L_Button/>
</div>
<div className="float-left">
<BButton/>
<B_Button/>
</div>
<div className="col-span-2 float-left">
<ShuffleButton/>
<SolveButton/>
</div>
</div>
</div>
)
}
export default ControlBar;
示例按钮组件:
const FButton = (props: any) => {
return (
<div className="colspan-7">
<button className="turn-button-class" onClick={props.rotateFaceClickHandler}>F</button>
</div>
)
}
export default FButton;
只需在useEffect之外声明多维数据集,然后你可以参考它。还要传递一个空数组以使用Effect作为第二个参数,这样它只运行一次。此外,我建议使用useRef作为你的操场分区的参考。希望这能有所帮助。