【发布时间】:2022-01-18 02:08:25
【问题描述】:
两个按钮在点击时运行相同的功能(至少在 console.log 之前)但给出不同的结果。
我尝试过以不同的顺序运行它们以及想到的所有其他内容。
感谢任何帮助。
import React, { Suspense, useRef, useEffect, useState } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import BlankPageFlip from "./BlankPageFlip";
const App = () => {
const refs = useRef([]);
const numPages = 10;
const pagesArr = [];
let currentPage = 0;
const [playing, setPlaying] = useState(false);
const speed = Math.PI / 1000;
const playAnim = (dir) => {
console.log(refs.current); <------ THIS CONSOLE LOG
if (refs.current[currentPage]) {
setPlaying(dir);
if (dir) currentPage++;
else currentPage--;
if (currentPage < 0) currentPage = 0;
if (currentPage === numPages) currentPage = numPages - 1;
}
};
useEffect(() => {
for (let i = 0; i < numPages; i++) {
pagesArr.push(
<BlankPageFlip
key={i}
ref={(el) => (refs.current[i] = el)}
position={[-1, 0.02 * i, 0]}
/>
);
}
});
const Pages = () => {
useFrame(() => {
if (playing) {
if (refs.current[currentPage]) {
if (refs.current[currentPage].rotation.z < Math.PI - 0.03) {
refs.current[currentPage].rotation.z += speed;
}
}
} else {
if (refs.current[currentPage]) {
if (refs.current[currentPage].rotation.z > 0) {
refs.current[currentPage].rotation.z -= speed;
}
}
}
});
return pagesArr;
};
return (
<>
<div className="NavButtons">
<button className="prev" onClick={() => playAnim(false)}>
Prev
</button>
<button className="next" onClick={() => playAnim(true)}>
Next
</button>
</div>
<Canvas
className="canvas"
colorManagement
camera={{ position: [0, 3.7, 0], fov: 60, far: 50 }}
>
<ambientLight intensity={2.0} />
<Suspense fallback={null}>
<Pages />
<OrbitControls />
</Suspense>
</Canvas>
</>
);
};
export default App;
【问题讨论】:
标签: javascript reactjs react-three-fiber