React
使用 Rive React 运行时在 React 应用中渲染 .riv 文件。
在 React 应用中使用 Rive 主要有三种方式:
- Hooks - 使用 React hooks 渲染 Rive 并控制状态机、事件和数据绑定。
- Rive 组件 - 使用默认组件进行简单嵌入,运行时控制有限。
- 命令式运行时 - 当您希望自己创建和管理 Rive 实例时,直接使用 Web JavaScript 运行时。

See a Working Demo
Load your Rive (.riv) file into a React component.
快速开始
- 安装依赖
npm i --save @rive-app/react-webgl2本指南使用
@rive-app/react-webgl2。Rive 还提供了其他用于不同渲染器的 React 包。请参阅选择渲染器来选择适合您项目的包。 - 渲染 Rive 组件
📌 Hooks
当您需要数据绑定时,可将返回的
rive实例与其他 hooks 一起使用。import React, { useEffect } from "react";
import { useRive, useViewModelInstanceNumber } from "@rive-app/react-webgl2";
export default function App() {
const { rive, RiveComponent } = useRive({
src: "quick_start_health_bar.riv",
stateMachines: "State Machine 1",
autoplay: true,
autoBind: true,
});
const vmi = rive?.viewModelInstance;
const { value: health, setValue: setHealth } = useViewModelInstanceNumber(
"health",
vmi
);
useEffect(() => {
setHealth(10);
}, [rive, setHealth]);
return (
<RiveComponent />
);
}Rive 画布根据其容器调整自身大小。如果没有显示任何内容,请确保父元素具有明确的宽度和高度。
📌 Rive 组件
Rive React 提供了一个基础组件作为默认导入,用于显示简单的动画,您可以通过一些属性(如
artboard和layout)进行设置。此方法最适合简单的嵌入。如果您需要控制状态机、访问 Rive 实例、监听事件或在运行时控制数据,请使用 hooks。
import Rive from '@rive-app/react-webgl2';
export const Simple = () => (
<Rive
src="https://cdn.rive.app/animations/vehicles.riv"
stateMachines="bumpy"
/>
);📌 命令式运行时
当您希望自己创建和管理 Rive 实例时,请使用命令式运行时。在 React 中,通常通过
useEffect和画布 ref 来实现。命令式运行时使用 Web JavaScript 运行时包,例如
@rive-app/webgl2,而不是 React 包。import React, { useEffect, useRef } from "react";
import { Rive, Fit, Layout } from "@rive-app/webgl2";
import "./styles.css";
export default function App() {
const canvasRef = useRef();
useEffect(() => {
const riveInstance = new Rive({
src: "quick_start_health_bar.riv",
stateMachines: "State Machine 1",
canvas: canvasRef.current,
autoplay: true,
autoBind: true,
onLoad: () => {
riveInstance.resizeDrawingSurfaceToCanvas();
},
});
const handleResize = () => {
if (riveInstance) {
riveInstance.resizeDrawingSurfaceToCanvas();
}
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
riveInstance.cleanup();
};
}, []);
return <canvas ref={canvasRef} style={{ width: "100%", height: "50vh" }} />;
}