gpt4 book ai didi

reactjs - 带有 Three.js Canvas 的 React 组件可以正常工作,但不是每次都有效

转载 作者:行者123 更新时间:2023-12-05 04:38:55 33 4
gpt4 key购买 nike

所以我有以下 react 组件,它允许我将 three.js Canvas 附加到 HTMLDivElement 类型的 ref 对象:

import { useEffect, useRef } from "react";
import * as THREE from 'three';

export default function Viewport() {
const mountRef = useRef<HTMLDivElement>(null);
const { current } = mountRef;

useEffect(() => {
if (!current) { return; }

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, current.clientWidth / current.clientHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
const { domElement } = renderer;
renderer.setClearColor(0xfff5ff,1)
renderer.setSize(current.clientWidth, current.clientHeight);
current.appendChild(domElement);

var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
var animate = function () {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};

animate();

return () => {
current.removeChild(domElement);
};

}, []);

return (
<div ref={mountRef} style={{width: '100%', height: '100%'}}>
</div>
);
}

该组件有效,但不是每次我安装它!这是“大部分时间”的输出: The component is mounted but the canvas is not there如果我只是添加:

    console.log(current);

代码可以正常工作,HTMLDivElement 对象将打印到控制台! enter image description here enter image description here我在这里缺少什么?

这是项目的 CodeSandBox 链接: https://codesandbox.io/s/unruffled-burnell-3if54?file=/src/Viewport.tsx

最佳答案

您正在关闭 mountRefcurrent 属性的陈旧副本。 current的初始值为null,也就是下一行第一次抓取到的值。然后 React 呈现您的组件并将 current 设置为引用 div然后您的 useEffect 回调被调用 -但它仍然有 null

相反,在 useEffect 回调中使用更新的属性;看评论:

export default function Viewport() {
const mountRef = useRef<HTMLDivElement>(null);
// Don't grab `current` here

useEffect(() => {
// Grab it here
const { current } = mountRef;
if (!current) { return; }
// ...

关于reactjs - 带有 Three.js Canvas 的 React 组件可以正常工作,但不是每次都有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70504678/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com