创建 3D 立方体组件
您可以使用自定义代码组件扩展 Toolpad Studio,包括来自外部包的组件。
您可以使用 npm
上提供的任何包来扩展您的 Toolpad Studio 应用程序。本指南将使用 @react-three/fiber
渲染一个立方体

立方体组件
创建组件
在 Toolpad Studio 编辑器中
要开始创建此组件,请使用以下命令将所需的库添加到您的 Toolpad Studio 应用程序:
yarn add three @react-three/fiber
然后,将鼠标悬停在组件库上,然后单击自定义组件部分中的创建按钮。

创建自定义组件
将出现一个对话框,要求您命名它。将其命名为“Cube”。

命名立方体组件
- 将出现一个提示条,确认组件已成功创建。启动器文件在
toolpad/components
中创建。使用打开按钮在代码编辑器中打开此文件

打开立方体组件
在代码编辑器中
为您初始化了一个包含自定义组件示例代码的文件。将其内容替换为以下代码
import * as React from 'react'; import { Canvas, useFrame } from '@react-three/fiber'; import { createComponent } from '@toolpad/studio/browser'; function Box({ position, color }) { // This reference gives us direct access to the THREE.Mesh object const ref = React.useRef(); // Hold state for hovered and clicked events const [hovered, hover] = React.useState(false); const [clicked, click] = React.useState(false); // Subscribe this component to the render-loop, rotate the mesh every frame useFrame((state, delta) => { if (!ref.current) return; ref.current.rotation.x += delta; }); // Return the view, these are regular Threejs elements expressed in JSX return ( <mesh position={position} ref={ref} scale={clicked ? 1.5 : 1} onClick={(event) => click(!clicked)} onPointerOver={(event) => hover(true)} onPointerOut={(event) => hover(false)} > <boxGeometry args={[1, 1, 1]} /> <meshStandardMaterial color={color ?? 'hotpink'} /> </mesh> ); } interface CubeProps { positionX: number; positionY: number; positionZ: number; color: string; } function Cube({ positionX, positionY, positionZ, color }: CubeProps) { return ( <Canvas> <ambientLight /> <pointLight position={[10, 10, 10]} /> <Box position={[positionX, positionY, positionZ]} color={color} /> </Canvas> ); } export default createComponent(Cube, { argTypes: { positionX: { type: 'number', default: 0, }, positionY: { type: 'number', default: 0, }, positionZ: { type: 'number', default: 0, }, color: { type: 'string', default: 'orange', }, }, });
positionX
、positionY
、positionZ
和 color
是您将在 Toolpad Studio 编辑器中提供的可绑定属性。
- Cube 现在将作为自定义组件在组件库中可用

立方体组件出现在组件库中
使用组件
- 将立方体组件拖到画布上。在检查器中,您将看到
position
属性作为可绑定属性。

立方体组件