Skip to main content

为您的 props 定义模式

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

先决条件

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

npm i --save-exact @remotion/zod-types@4.0.206 zod@3.22.3
npm i --save-exact @remotion/zod-types@4.0.206 zod@3.22.3
This assumes you are currently using v4.0.206 of Remotion.
Also update remotion and all `@remotion/*` packages to the same version.
Remove all ^ character in front of the version numbers of it as it can lead to a version conflict.

定义模式

要为您的 props 定义模式,请使用 z.object():

tsx
import { z } from "zod";
 
export const myCompSchema = z.object({
propOne: z.string(),
propTwo: z.string(),
});
tsx
import { z } from "zod";
 
export const myCompSchema = z.object({
propOne: z.string(),
propTwo: z.string(),
});

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

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

将模式添加到您的合成

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

src/Root.tsx
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",
}}
/>
);
};
src/Root.tsx
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",
}}
/>
);
};

直观地编辑 props

当您为您的 props 定义了模式后,您可以在 Remotion Studio 中直观地编辑它们。如果您想快速尝试不同的 props 值,则这非常有用。

支持的类型

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

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

除了内置类型外,@remotion/zod-types 包还提供了 zColor(),其中包括 Remotion Studio 的颜色选择器界面。