我将我的应用程序从版本 4 更新到 Material-UI
版本 5,但 RTL 支持不再有效。
我查看了文档并遵循了每个步骤:
https://mui.com/guides/right-to-left/
实际结果是应用还是LTR(可以看下面Codesandbox链接中的TextField
组件)。
预期的结果是应用程序应该是 RTL。
而且,RTL 支持仍然不起作用。
此外,我在 Codesandbox
中创建了一个示例版本:
https://codesandbox.io/s/issue-with-rtl-in-material-ui-v5-jtii6?file=/src/index.js
非常感谢您帮助找出问题所在。
谢谢。
最佳答案
我在使用波斯语时遇到了这个问题。但它的答案太简单了。你只需要一些简单的步骤。 我的示例环境是:
- “ react ”:“^18.2.0”
- "react-dom": "^18.2.0"
让我们开始吧:
第 1 步:安装以下软件包(我会为您提供确切的版本,以确保它在未来的更新中有效):
- "@emotion/react": "^11.9.3"
- "@emotion/styled": "^11.9.3"
- "@mui/icons-material": "^5.8.4"
- "@mui/material": "^5.9.1"
- “手写笔”:“^4.1.1”
- "stylis-plugin-rtl": "^2.1.1"
提示:这是我的 package.json 文件:
第 2 步:像这样更改 public/index.html 中 html 标记的方向:
`<html lang="fa" dir="rtl">`
第 3 步:在 index.js 文件中添加以下部分:
3-1:需要导入:
import {createTheme, ThemeProvider} from '@mui/material/styles';
import rtlPlugin from 'stylis-plugin-rtl';
import {prefixer} from 'stylis';
import {CacheProvider} from '@emotion/react';
import createCache from '@emotion/cache';
3-2:需要缓存:
const cacheRtl = createCache({
key: 'muirtl',
stylisPlugins: [prefixer, rtlPlugin],
});
3-3:要求的主题:
const theme = createTheme({
direction: 'rtl',
});
3-4:这是最后一步,您可以像这样在组件周围包裹两个包装器:
<CacheProvider value={cacheRtl}>
<ThemeProvider theme={theme}>
<App/>
</ThemeProvider>
</CacheProvider>
最后,你完成的 index.js 文件应该是这样的:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {createTheme, ThemeProvider} from '@mui/material/styles';
import rtlPlugin from 'stylis-plugin-rtl';
import {prefixer} from 'stylis';
import {CacheProvider} from '@emotion/react';
import createCache from '@emotion/cache';
const cacheRtl = createCache({
key: 'muirtl',
stylisPlugins: [prefixer, rtlPlugin],
});
const theme = createTheme({
direction: 'rtl',
});
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<CacheProvider value={cacheRtl}>
<ThemeProvider theme={theme}>
<App/>
</ThemeProvider>
</CacheProvider>
);
现在您的整个应用程序都是 rtl。我向您展示了一个带有图像的波斯示例:
像这样更改您的 App.jsx 组件:
import React from 'react';
import {Autocomplete, Box, TextField} from "@mui/material";
const App = () => {
return (
<Box m={2}>
<Autocomplete
sx={{width: 300}}
options={iranStates}
onChange={(event, value) => console.log(value)}
renderInput={(params) => <TextField {...params} label={"لیست استانها"}/>}/>
</Box>
);
};
export default App;
const iranStates = [
"آذربایجان شرقی",
"آذربایجان غربی",
"اردبیل",
"اصفهان",
"البرز",
"ایلام",
"بوشهر",
"تهران",
"چهارمحال و بختیاری",
]
并查看结果:
关于javascript - 如何在 Material UI 版本 5 中配置 RTL(从右到左)支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69371106/