首页 > 解决方案 > react-three-fiber multiple meshes 丢失模型,除了最后一个

问题描述

我一直在用 React 开发一个应用程序react-three-fiber来直观地显示数据。我试图通过将表示其属性的数据作为道具传递给组件来创建不同的模型。我的问题出现在这里,因为在每个组件内部我能够添加一个简单的形状(例如立方体)并让它正确显示,当我在每个组件内部声明要使用的模型时,它似乎只被最后一个组件拾取创建;

顶级组件画布简化

return (
    <div> 
        <Canvas> 
            <Suspense fallback={null}>
                <Items items={this.state.data}/>
            </Suspense>
        </Canvas>
    </div>
)

中层组件

// count is to identify the position in the loop so that the meshes do not overlap 

import React, {Component} from 'react';
import ITEM from './ITEM';

class Items extends Component {
    
    render() {
        return this.props.items.map((item, i) => (
            <ITEM key={i} item={item} count={i}/>
        ));
    }
}

底层组件

// I have been using the drei GLTF loader to get the model

import React, {useRef} from 'react';
import {useFrame} from 'react-three-fiber';
import {useGLTF} from 'drei';

const Model = ({modelPath}) => {
    const gltf = useGLTF(modelPath, true)
    return <primitive object={gltf.scene} dispose={null}/>
};

const ITEM = ({item, count}) => {

    const modelPath = '/model/scene.gltf';

    const mesh = useRef(null);
    useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01));
    return (
        <mesh castShadow position={[1, 1, 1]} ref={mesh}>
            <Model modelPath={modelPath}/>
        </mesh>
    );
};

标签: javascriptreactjsthree.jsreact-three-fiber

解决方案


使用gltfjsx将您的 GLTF 模型转换为 react 组件,然后您可以使用 props 来编辑它们的某些属性。


推荐阅读