跳到内容
+

Right-to-left 支持

了解如何使用 Joy UI 实现从右到左 (RTL) 的文本,以支持阿拉伯语、波斯语和希伯来语等语言。

设置

本指南概述了更改 Joy UI 中基于文本的组件方向以支持 RTL 语言所需的三个步骤,如下面的演示所示

هذا نص مساعد
Enter 开始编辑

1. 设置 HTML 方向

您可以全局(在整个应用程序中)或本地(特定于单个组件)设置文本方向,具体取决于您的用例。

全局

dir="rtl" 添加到应用程序的根 <html> 标签以设置全局文本方向

<html dir="rtl"></html>

如果您无法直接在根 <html> 元素上设置 dir 属性,作为一种解决方法,请在页面渲染之前使用 JavaScript API

document.documentElement.setAttribute('dir', 'rtl');

本地

如果您需要将文本方向的范围限制在该元素及其子元素,请将 dir="rtl" 属性添加到任何其他 HTML 元素或 React 组件。

2. 设置主题方向

使用 extendTheme API 将主题方向设置为 'rtl'

import { extendTheme } from '@mui/joy/styles';

const theme = extendTheme({
  direction: 'rtl',
});

3. 配置 RTL 样式插件

使用以下命令之一安装 stylis-plugin-rtl

npm install stylis stylis-plugin-rtl

使用 Emotion

如果您正在使用 Emotion,请使用 CacheProvider 创建一个新的缓存实例,该实例使用来自 stylis-plugin-rtlrtlPlugin,并将其添加到应用程序树的顶部

import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import { prefixer } from 'stylis';
import rtlPlugin from 'stylis-plugin-rtl';

// Create rtl cache
const cacheRtl = createCache({
  key: 'muirtl',
  stylisPlugins: [prefixer, rtlPlugin],
});

function Rtl(props) {
  return <CacheProvider value={cacheRtl}>{props.children}</CacheProvider>;
}

使用 styled-components

如果您正在使用 styled-components,请使用 StyleSheetManager 并将 rtlPlugin 提供给 stylisPlugins 属性

import { StyleSheetManager } from 'styled-components';
import rtlPlugin from 'stylis-plugin-rtl';

function Rtl(props) {
  return (
    <StyleSheetManager stylisPlugins={[rtlPlugin]}>
      {props.children}
    </StyleSheetManager>
  );
}

在本地选择退出 RTL

要在特定组件上关闭 RTL,请使用模板字面量语法并添加 /* @noflip */ 指令

const LeftToRightTextInRtlApp = styled('div')`
  /* @noflip */
  text-align: left;
`;
RTL 正常行为
RTL noflip
Enter 开始编辑