useTextDirection
跟踪文字排列方向
useTextDirection 读取并更新目标元素(默认为 <html>)上的 dir 属性,控制文本方向。它返回一个包含当前方向值("ltr"、"rtl" 或 "auto")和设置函数的元组。这对于构建支持从右到左语言(如阿拉伯语、希伯来语和波斯语)的国际化应用至关重要。
使用场景
- 在多语言应用中支持双向(BiDi)内容
- 构建在 LTR 和 RTL 布局之间切换的语言选择器
- 基于用户输入或内容语言动态调整文本方向
注意事项
- SSR 安全:在服务端渲染期间返回
initialValue(默认"ltr")和空操作设置函数。服务端不会访问document。 - 目标选择器:默认情况下,hook 在
<html>元素上设置dir。使用selector选项定位特定元素以进行作用域内的方向更改。 - 相关 hooks:参见
usePreferredLanguages了解检测用户的语言偏好,这可以为文本方向的选择提供参考。
Usage
Live Editor
function Demo() { const [dir, setDir] = useTextDirection({ selector: "#_useTextDirectionDemo", }); const text = useMemo( () => dir === "ltr" ? "这段文字是中文,正确地从左到右显示。" : "这段文字是中文,但错误地从右到左显示。", [dir], ); const handleOnClick = () => { const value = dir === "rtl" ? "ltr" : "rtl"; setDir(value); }; return ( <div id="_useTextDirectionDemo"> <p>{text}</p> <button onClick={handleOnClick}> <span>{dir?.toUpperCase()}</span> </button> <span>点击更改方向</span> </div> ); }; render(<Demo/>)
Result
API
useTextDirection
Returns
readonly [UseTextDirectionValue, (value: UseTextDirectionValue) => void]: 包含以下元素的元组:
- 文字方向。
- 更新文字方向值的函数。
Arguments
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| options | 可选参数 | UseTextDirectionOptions | undefined | - |
UseTextDirectionOptions
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| selector | 适用于目标元素的 CSS 选择器 | string | 'html' |
| initialValue | 初始值 | UseTextDirectionValue | 'ltr' |
UseTextDirectionValue
Type
export type UseTextDirectionValue = 'ltr' | 'rtl' | 'auto'