由右至左 (RTL) 支援
了解如何實作文字與 Material UI,以支援如阿拉伯語、波斯語和希伯來語等語言。
設定
本指南概述了三個必要的步驟,以更改 Material 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. 設定主題方向
使用 createTheme()
API 將主題方向設定為 'rtl'
import { createTheme } from '@mui/material/styles';
const theme = createTheme({
direction: 'rtl',
});
3. 設定 RTL 樣式外掛程式
使用以下其中一個指令安裝 stylis-plugin-rtl
npm install stylis stylis-plugin-rtl
搭配 Emotion
如果您使用 Emotion,請使用 CacheProvider 建立一個新的快取實例,該實例使用來自 stylis-plugin-rtl
的 rtlPlugin
,並將其新增至您的應用程式樹狀結構的頂部。
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import { prefixer } from 'stylis';
import rtlPlugin from 'stylis-plugin-rtl';
// Create rtl cache
const rtlCache = createCache({
key: 'muirtl',
stylisPlugins: [prefixer, rtlPlugin],
});
function Rtl(props) {
return <CacheProvider value={rtlCache}>{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 開始編輯