我之前在使用波斯语时遇到了这个问题。但答案非常简单,只需要按照以下步骤操作:
我的示例环境如下:
- "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"
- "stylis": "^4.1.1"
- "stylis-plugin-rtl": "^2.1.1"
提示:这是我的 package.json 文件:
步骤2:像这样更改 public/index.html 中的 html 标签方向:
`<html lang="fa" dir="rtl">`
步骤三:在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>
);
现在您的整个应用程序是从右到左。我将通过图片展示一个波斯语的例子,以便您可以看到:
按以下方式更改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 = [
"آذربایجان شرقی",
"آذربایجان غربی",
"اردبیل",
"اصفهان",
"البرز",
"ایلام",
"بوشهر",
"تهران",
"چهارمحال و بختیاری",
]
并查看结果: