傳遞 Props
了解在 Remotion 中傳遞 Props 的各種方式。
Props 的四種來源
在 Remotion 中,Props 可以從四個地方傳入,優先順序由低到高:
- Default Props — 在 Composition 定義中設定的預設值
- Input Props — 從 CLI、Studio 或 API 傳入的值
- calculateMetadata — 在渲染前動態計算的值
- 最終 Props — 以上三者合併後的結果
Default Props
在 <Composition> 中定義:
<Composition
id="MyVideo"
component={MyVideo}
durationInFrames={90}
fps={30}
width={1920}
height={1080}
defaultProps={{
title: "預設標題",
color: "#ffffff",
showLogo: true,
}}
/>從 CLI 傳入
# JSON 字串
npx remotion render MyVideo out/video.mp4 \
--props='{"title": "自訂標題", "color": "#ff0000"}'
# 從檔案
npx remotion render MyVideo out/video.mp4 --props=./my-props.jsonCLI 傳入的 Props 會覆蓋同名的 Default Props。
從 Studio 傳入
如果你定義了 Zod Schema,Studio 會自動產生 UI 控制項:
import { z } from "zod";
export const schema = z.object({
title: z.string().describe("影片標題"),
color: z.string().describe("主題顏色"),
showLogo: z.boolean().describe("是否顯示 Logo"),
});在 Studio 右側面板中,你可以直接修改這些值並即時預覽。
從 Node.js API 傳入
const composition = await selectComposition({
serveUrl: bundled,
id: "MyVideo",
inputProps: {
title: "API 傳入的標題",
color: "#00ff00",
},
});在元件中接收
interface MyVideoProps {
title: string;
color: string;
showLogo: boolean;
}
export const MyVideo: React.FC<MyVideoProps> = ({
title,
color,
showLogo,
}) => {
return (
<AbsoluteFill style={{ backgroundColor: color }}>
<h1>{title}</h1>
{showLogo && <Logo />}
</AbsoluteFill>
);
};Props 合併規則
Default Props: { title: "預設", color: "#fff", showLogo: true }
+
Input Props: { title: "自訂" }
=
最終 Props: { title: "自訂", color: "#fff", showLogo: true }
Input Props 只覆蓋有指定的欄位,其他欄位保留 Default Props 的值。
小結
- Default Props → Input Props → calculateMetadata,優先順序由低到高
- CLI 用
--props傳入 JSON - Studio 配合 Zod Schema 自動產生 UI
- Node.js API 用
inputProps傳入 - 部分覆蓋:只有指定的欄位會被覆寫