跳到主要內容
+

由右至左 (RTL) 支援

了解如何使用 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 建立一個新的 cache 實例,該實例使用來自 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 開始編輯