基于documentation 以下是正确工作RTL 需要执行的一些步骤:
1. HTML : 确保在 body 上设置了 dir 属性,否则原生组件会损坏:
<body dir="rtl"></body>
作为上述方法的替代方案,您还可以将应用程序包装在具有dir 属性的元素中:
function App() {
return (
<div dir="rtl">
<MyComponent />
</div>
);
}
2。主题: 在您的自定义主题中设置方向:
const theme = createTheme({
direction: 'rtl',
});
3.安装 rtl 插件 : 当使用emotion 或styled-components 时,你需要stylis-plugin-rtl 来翻转样式。
npm install stylis stylis-plugin-rtl
如果您使用 jss(最高 v4)或旧版 @mui/stylespackage,则需要 jss-rtl 来翻转样式。
npm install jss-rtl
在您的项目中安装插件后,MUI 组件仍然需要您使用的样式引擎实例加载它。查找以下指南,了解如何加载它。
4.加载 rtl 插件
4.1 情感:如果您使用情感作为样式引擎,您应该创建使用stylis-plugin-rtl 的新缓存实例,并在应用程序树的顶部提供该实例。 CacheProvider 组件可以实现这一点:
import rtlPlugin from 'stylis-plugin-rtl';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
// Create rtl cache
const cacheRtl = createCache({
key: 'muirtl',
stylisPlugins: [rtlPlugin],
});
function RTL(props) {
return <CacheProvider value={cacheRtl}>{props.children}</CacheProvider>;
}
4.2 styled-components :如果您使用styled-components 作为您的样式引擎,您可以使用StyleSheetManager 并在stylisPlugins 属性中提供stylis-plugin-rtl 作为项目:
import { StyleSheetManager } from 'styled-components';
import rtlPlugin from 'stylis-plugin-rtl';
function RTL(props) {
return (
<StyleSheetManager stylisPlugins={[rtlPlugin]}>
{props.children}
</StyleSheetManager>
);
}
4.3 JSS : 在你的项目中安装插件后,你需要配置 JSS 实例来加载它。下一步是使新的 JSS 实例可用于组件树中的所有组件。 StylesProvider 组件可以实现这一点:
import { create } from 'jss';
import rtl from 'jss-rtl';
import { StylesProvider, jssPreset } from '@mui/styles';
// Configure JSS
const jss = create({
plugins: [...jssPreset().plugins, rtl()],
});
function RTL(props) {
return <StylesProvider jss={jss}>{props.children}</StylesProvider>;
}