Skip to main content

为你的 props 定义一个模式

作为替代使用 TypeScript 类型来定义组件接受的 props 形状的方法,你可以使用Zod来定义 props 的模式。如果你希望在 Remotion Studio 中可视化地编辑 props,你可以这样做。

🌐 As an alternative to using TypeScript types to define the shape of the props your component accepts, you may use Zod to define a schema for your props. You may do so if you want to edit the props visually in the Remotion Studio.

先决条件

🌐 Prerequisites

如果你想使用此功能,请安装 zod@remotion/zod-types 以获取 Remotion 特定类型:

🌐 If you want to use this feature, install zod and @remotion/zod-types for Remotion-specific types:

npx remotion add @remotion/zod-types zod

定义一个模式

🌐 Defining a schema

要为你的 props 定义一个 schema,使用 z.object()

🌐 To define a schema for your props, use z.object():

import {z} from 'zod';

export const myCompSchema = z.object({
  propOne: z.string(),
  propTwo: z.string(),
});

使用 z.infer(),你可以将模式转换为一种类型:

🌐 Using z.infer(), you can turn the schema into a type:

export const MyComp: React.FC<z.infer<typeof myCompSchema>> = ({propOne, propTwo}) => {
  return (
    <div>
      props: {propOne}, {propTwo}
    </div>
  );
};

将模式添加到你的组成中

🌐 Adding a schema to your composition

使用 schema 属性将模式附加到你的 <Composition>。Remotion 将要求你指定匹配的 defaultProps

🌐 Use the schema prop to attach the schema to your <Composition>. Remotion will require you to specify matching defaultProps.

src/Root.tsx
import React from 'react'; import {Composition} from 'remotion'; import {MyComponent, myCompSchema} from './MyComponent'; export const RemotionRoot: React.FC = () => { return ( <Composition id="my-video" component={MyComponent} durationInFrames={100} fps={30} width={1920} height={1080} schema={myCompSchema} defaultProps={{ propOne: 'Hello World', propTwo: 'Welcome to Remotion', }} /> ); };

可视化编辑属性

🌐 Editing props visually

当你为你的 props 定义了一个 schema 后,你可以在 Remotion Studio 中可视化编辑它们。如果你想快速尝试不同的 props 值,这会很有用。

🌐 When you have defined a schema for your props, you can edit them visually in the Remotion Studio. This is useful if you want to quickly try out different values for your props.

支持的类型

🌐 Supported types

所有 Zod 支持的模式都被 Remotion 支持。

🌐 All schemas that are supported by Zod are supported by Remotion.

Remotion 要求顶层类型是 z.object(),因为 React 组件的 props 集合总是一个对象。

🌐 Remotion requires that the top-level type is a z.object(), because the collection of props of a React component is always an object.

除了内置类型之外,@remotion/zod-types 还提供了像 zColor()zTextarea()zMatrix() 这样的类型。

🌐 In addition to the built in types, the @remotion/zod-types package also provides types like zColor(), zTextarea() and zMatrix().