React 和 Next.js
使用 JuliyaProvider 统一设置语言,JuliyaText 与 useJuliya 会继承该设置。单独指定的 locale 优先,没有 Provider 时默认使用韩语。请将 i18n 的语言标签映射到 ko、en、ja、zh 或 zh-Hans。Provider 和使用它的组件应从同一软件包导入。
JuliyaText
使用 as 指定元素来渲染字符串,组件会测量实际内容宽度。
tsx
import { JuliyaText } from '@oddmash/juliya/react';
<JuliyaText as="h1" locale="zh-Hans">让每一行自然易读。</JuliyaText>| 选项 | 必填 | 默认值 | 用途 |
|---|---|---|---|
children | 必填 | - | 文本或受支持的内联子节点 |
as | 可选 | span | 渲染元素 |
locale | 可选 | ko | 语言规则;React 还读取最近的 Provider |
strategy | 可选 | balanced | balanced 或 greedy 布局 |
breakLongWords | 可选 | true | 允许在字素边界拆分长词 |
forcedBreaks | 可选 | - | 原文 UTF-16 边界偏移量 |
JuliyaProvider
向子组件提供 locale 或已验证配置,显式组件属性优先。
tsx
import { JuliyaProvider, JuliyaText } from '@oddmash/juliya/react';
<JuliyaProvider locale="zh-Hans">
<JuliyaText as="h1">让每一行自然易读。</JuliyaText>
</JuliyaProvider>连接 i18n
将应用语言标签映射到 ko、en、ja、zh 或 zh-Hans,并在语言变化时更新 Provider。
动态文本
children 改变时重新计算,不需要手动修改 DOM。
内联 JSX
支持的链接与强调保留语义。可信外部 HTML 可以使用范围 API。
useJuliya 的用法
返回 ref、lines、measured、locale 和强制换行控制项。将 ref 连接到可测量元素并自行渲染。
tsx
import { Fragment } from 'react';
import { useJuliya } from '@oddmash/juliya/react';
const { ref, lines, locale } = useJuliya({ text, locale: 'zh-Hans' });
return <p ref={ref} lang={locale} style={{ whiteSpace: 'pre-wrap' }}>{lines.map((line, index) => <Fragment key={line.start}>{line.text}{line.breakAfter || (index < lines.length - 1 ? <br /> : null)}</Fragment>)}</p>;Hook 选项
传入 text、locale、strategy、breakLongWords 和 forcedBreaks 等选项。宽度在浏览器中测量。
| 选项 | 必填 | 默认值 | 用途 |
|---|---|---|---|
text | 必填 | - | Hook 使用的原始字符串 |
locale | 可选 | ko | 语言规则;React 还读取最近的 Provider |
strategy | 可选 | balanced | balanced 或 greedy 布局 |
breakLongWords | 可选 | true | 允许在字素边界拆分长词 |
forcedBreaks | 可选 | - | 原文 UTF-16 边界偏移量 |
initialForcedBreaks | 可选 | [] | 非受控初始强制边界 |
onForcedBreaksChange | 可选 | - | 受控边界变化回调 |
受控与非受控
使用 forcedBreaks 外部控制,或通过 initialForcedBreaks 和设置函数管理本地状态。
Next.js App Router
客户端组件在 hydration 后测量;Server Component 可使用显式 locale 的 JuliyaSentenceText。
tsx
import { JuliyaSentenceText } from '@oddmash/juliya/react/server';
<JuliyaSentenceText locale="zh-Hans">让每一行自然易读。</JuliyaSentenceText>