如何解决访问另一个组件中组件的引用?
在我的组件 Box
中,我返回了 mesh
类型的 Object3d
,我需要在我的 Floor
组件中获取对此对象的引用,但我没有t想出了一种方法来做到这一点。我试图在我的 App
组件中分配另一个引用并将其传递给 Floor
,但这样我只能得到 {current: undefined}
。
如何在另一个组件中引用 mesh
的 Box
ref?
我是这样试的
export default function App() {
const box = useRef();
return (
<Canvas camera={{ position: [0,10,10] }} onCreated={({ scene }) => {
scene.background = new THREE.Color(0xffffff);
scene.fog = new THREE.Fog(0xffffff,750);
}} >
<hemisphereLight args={[0xeeeeff,0x777788,0.75]} position={[0.5,1,0.75]}></hemisphereLight>
<Box ref={box} position={[0,-30]} />
<Floor boxRef={box}></Floor>
</Canvas>
)
}
function Floor({ boxRef }) {
const mesh = useRef();
useFrame(() => {
// How to use the mesh ref of Box here?????
console.log(boxRef);
})
return (
<mesh ref={mesh} >
<planeBufferGeometry args={[2000,2000]} rotateX={-Math.PI / 2}></planeBufferGeometry>
<meshStandardMaterial color="#999999"></meshStandardMaterial>
</mesh>
)
}
function Box(props) {
const mesh = useRef()
return (
<mesh
{...props}
ref={mesh}>
<boxBufferGeometry args={[20,20,20]} />
<meshPhongMaterial color={0x00ff00}></meshPhongMaterial>
</mesh>
)
}
解决方法
我想你不应该在 Box 组件中覆盖 ref 而只使用 {...props}
export default function App() {
const box = useRef();
return (
<Canvas camera={{ position: [0,10,10] }} onCreated={({ scene }) => {
scene.background = new THREE.Color(0xffffff);
scene.fog = new THREE.Fog(0xffffff,750);
}} >
<hemisphereLight args={[0xeeeeff,0x777788,0.75]} position={[0.5,1,0.75]}></hemisphereLight>
<Box ref={box} position={[0,-30]} />
<Floor boxRef={box}></Floor>
</Canvas>
)
}
function Floor({ boxRef }) {
const mesh = useRef();
useFrame(() => {
// How to use the mesh ref of Box here?????
console.log(boxRef);
})
return (
<mesh ref={mesh} >
<planeBufferGeometry args={[2000,2000]} rotateX={-Math.PI / 2}></planeBufferGeometry>
<meshStandardMaterial color="#999999"></meshStandardMaterial>
</mesh>
)
}
function Box(props) {
return (
<mesh
{...props}>
<boxBufferGeometry args={[20,20,20]} />
<meshPhongMaterial color={0x00ff00}></meshPhongMaterial>
</mesh>
)
}
,
解决方案涉及React.forwardRef
,我就是这样解决的
export default function App() {
const box = useRef();
return (
<Canvas camera={{ position: [0,-30]} />
<Floor boxRef={box}></Floor>
</Canvas>
)
}
function Floor({ boxRef }) {
const mesh = useRef();
useFrame(() => {
console.log(boxRef);
})
return (
<mesh ref={mesh} >
<planeBufferGeometry args={[2000,2000]} rotateX={-Math.PI / 2}></planeBufferGeometry>
<meshStandardMaterial color="#999999"></meshStandardMaterial>
</mesh>
)
}
const Box = React.forwardRef((props,ref) => {
return (
<mesh
{...props}
ref={ref}>
<boxBufferGeometry args={[20,20]} />
<meshPhongMaterial color={0x00ff00}></meshPhongMaterial>
</mesh>
)
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。