跳到主要内容

文本

⚠️ 已弃用:请使用数据绑定代替运行时直接操作文本运行

概述

Rive 文本运行允许你在运行时动态读取和写入 Rive 中的文本内容。

示例

读取文本

要随时读取给定文本运行的文本值,请使用 useRive 返回的 rive 实例上的 .getTextRunValue() API:

public getTextRunValue(textRunName: string): string | undefined

提供文本运行名称,你将获得 Rive 文本运行的值,如果无法查询文本运行则返回 undefined

设置文本

要随时设置给定文本运行的值,请使用 useRive 返回的 rive 实例上的 .setTextRunValue() API:

public setTextRunValue(textRunName: string, textRunValue: string): void

提供文本运行名称和第二个参数 textValue(String 值),如果可以在活动画板上成功查询到文本运行,则将新文本值设置给它。

示例用法

import { useRive } from '@rive-app/canvas';

const MyTextComponent = () => {
const {rive, RiveComponent} = useRive({
src: "my-rive-file.riv",
artboard: "New Artboard",
stateMachines: "State Machine 1",
autoplay: true,
});

// 不能立即查询文本运行,必须等到 `rive` 有值并已实例化后才能查询或设置文本运行值
useEffect(() => {
if (rive) {
console.log("Rive 文本初始值为:", rive.getTextRunValue("MyRun"));
rive.setTextRunValue("MyRun", "新文本!!");
console.log("Rive 文本现在为:", rive.getTextRunValue("MyRun"));
}
}, [rive]);

return (
<RiveComponent />
);
};

嵌套画板

对于嵌套画板中的文本运行,你需要指定完整的路径来访问它们。

读取文本

要随时读取给定文本运行的文本值,请使用 useRive 返回的 rive 实例上的 .getTextRunValue() API:

public getTextRunValue(textRunName: string): string | undefined

提供文本运行名称,你将获得 Rive 文本运行的值,如果无法查询文本运行则返回 undefined

设置文本

要随时设置给定文本运行的值,请使用 useRive 返回的 rive 实例上的 .setTextRunValue() API:

public setTextRunValue(textRunName: string, textRunValue: string): void

提供文本运行名称和第二个参数 textValue(String 值),如果可以在活动画板上成功查询到文本运行,则将新文本值设置给它。

示例用法

import { useRive } from '@rive-app/canvas';

const MyTextComponent = () => {
const {rive, RiveComponent} = useRive({
src: "my-rive-file.riv",
artboard: "New Artboard",
stateMachines: "State Machine 1",
autoplay: true,
});

// 不能立即查询文本运行,必须等到 `rive` 有值并已实例化后才能查询或设置文本运行值
useEffect(() => {
if (rive) {
console.log("Rive 文本初始值为:", rive.getTextRunValue("MyRun"));
rive.setTextRunValue("MyRun", "新文本!!");
console.log("Rive 文本现在为:", rive.getTextRunValue("MyRun"));
}
}, [rive]);

return (
<RiveComponent />
);
};

无障碍语义

Rive 支持为文本元素提供无障碍语义,以提升屏幕阅读器的兼容性。