Material-Ui TextField 不受 RTL 方向影响

2024-02-16

我在我的 React 项目中使用 Material-Ui!

我按照中的步骤操作文档 https://material-ui.com/guides/right-to-left/#opting-out-of-rtl-transformation允许 RTL 在我的项目中并且一切正常!

除了 TextField 组件

轻轨方向:

左转方向

就像你看到的那样!问题是标签仍在左侧(输入文本工作正常)

应用程序.js 文件

import React, {useState} from 'react';


//i18n
import {withTranslation} from "react-i18next";
import './i18n';

//jss
import { create } from 'jss';
import rtl from 'jss-rtl';
import { StylesProvider, jssPreset } from '@material-ui/core/styles';

 // Configure JSS
 const jss = create({ plugins: [...jssPreset().plugins, rtl()] });




  function App(props) {

      // initialize Language
      const {  i18n } = props;
      const [ prefLang, setPrefLang] = useState(i18n.language);
      let theme =createMuiTheme({
        palette : {
            primary : {
                main : '#ed5ac0',
            },

        },
        typography : {
            fontFamily : "lalezar, cursive",
            h3 : {
                fontSize : 1.4,
            },
            h4 : {
                fontSize : 1.5
            },
            fontAwseomeSize : {
                xs : "14px",
                sm : "14px",
                md : "16px"
            },
            responsiveFont : {
                xs : "20px",
                sm : "12.5px",
                md : "14px"
            },
            highLight : {
                md : "25px"
            },
            subHighLight : {
                md : "18px"
            }
        },

    }
);



return (
          <BrowserRouter>
            <LangContext.Provider
                value ={{
                    prefLang,
                    setPrefLang
                }}
            >
                <CssBaseline/>
                <ThemeProvider theme={theme}>
                    <StylesProvider jss={jss}>
                        <Grid dir={(prefLang === "ar") ? "rtl" : "ltr"}>
                            {/*<AppHeader/>*/}


                            <ContentRouter/>


                        </Grid>
                    </StylesProvider>
                </ThemeProvider>


            </LangContext.Provider>

          </BrowserRouter>
      );
    }

   export default withTranslation()(App);

我的表单组件

const LoginForm = () => {

 return (
    <>
        <Backdrop style={{ zIndex : 999 , color : theme.palette.primary.main}} open={backdrop} >
            <CircularProgress color="inherit" />
        </Backdrop>
        <form onSubmit={formik.handleSubmit} style={{width: "100%", marginTop: "20px"}}>

            { userNotFound ? <Alert style={{marginBottom : "20px"}} variant="outlined" severity="error">
                This is an error alert — check it out!
            </Alert> : null}
            <TextField
                id="identifier"
                name="identifier"
                onChange={formik.handleChange}
                value={formik.values.identifier}
                label={t('formIdentifier')}
                fullWidth
            />
            {formik.touched.identifier && formik.errors.identifier ?
                (
                    <Alert style={{ marginTop :"10px"}} variant="outlined" severity="error">{formik.errors.identifier}</Alert>

                ) : null}
            <TextField
                style={{marginTop: "50px"}}
                id="password"
                name="password"
                type="password"
                onChange={formik.handleChange}
                value={formik.values.password}
                label={t('formPassword')}
                fullWidth
            />
            {formik.touched.password && formik.errors.password ?
                (
                    <Alert style={{ marginTop :"10px"}} variant="outlined" severity="error">{formik.errors.password}</Alert>

                ) : null}
            <Button type="submit" color="primary">{t('login')}</Button>
        </form>
    </>
     );
  };

我的 Theme.js 文件

import createMuiTheme from "@material-ui/core/styles/createMuiTheme";

let theme =createMuiTheme({

    direction : 'rtl',
    palette : {
        primary : {
            main : '#ed5ac0',
        },

    },
    typography : {
        fontFamily : "Merienda One, sans-serif",
        h3 : {
            fontSize : 1.4,
        },
        h4 : {
            fontSize : 1.5
        },
        fontAwseomeSize : {
            xs : "14px",
            sm : "14px",
            md : "16px"
        },
        responsiveFont : {
            xs : "20px",
            sm : "12.5px",
            md : "14px"
        },
        highLight : {
            md : "40px"
        }
    },

} 

);

导出默认主题;

对于制作标签 RTL 有什么建议吗?


The 文档 https://mui.com/guides/right-to-left/包含 RTL 支持的四个步骤:

  1. Set the dir属性上的body元素。

在我下面的示例中,这是通过以下方式处理的:

  React.useLayoutEffect(() => {
    document.body.setAttribute("dir", isRtl ? "rtl" : "ltr");
  }, [isRtl]);
  1. Set the direction在主题中。

在下面的示例中,我在两个主题之间切换:

const ltrTheme = createTheme({ direction: "ltr" });
const rtlTheme = createTheme({ direction: "rtl" });
...
<ThemeProvider theme={isRtl ? rtlTheme : ltrTheme}>
...
</ThemeProvider>
  1. 安装 rtl 插件。

    • 对于 v4(使用 JSS),这意味着安装jss-rtl.
    • 对于 v5(使用 Emotion),这意味着安装stylis-plugin-rtl.
  2. 加载 rtl 插件。

下面是一个 v4 示例,展示了如何加载 JSS 的 rtl 插件(下面是 v5 示例)。

出于性能原因,避免重新渲染非常重要StylesProvider,因此它不应该位于状态可以更改并因此触发重新渲染的组件中。在我自己的应用程序中,我有StylesProvider我的元素index.jsfile 作为react-dom调用中的第一个元素render.

import rtl from "jss-rtl";
import {
  StylesProvider,
  jssPreset
} from "@material-ui/core/styles";
// Configure JSS
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });
export default function App() {
  return (
    <StylesProvider jss={jss}>
      <AppContent />
    </StylesProvider>
  );
}

下面的示例包括一个TextField您可以看到标签的位置正确切换。

import React from "react";
import { create } from "jss";
import rtl from "jss-rtl";
import {
  StylesProvider,
  jssPreset,
  ThemeProvider,
  createTheme
} from "@material-ui/core/styles";
import CssBaseline from "@material-ui/core/CssBaseline";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import Box from "@material-ui/core/Box";

// Configure JSS
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });

const ltrTheme = createTheme({ direction: "ltr" });
const rtlTheme = createTheme({ direction: "rtl" });

function AppContent() {
  const [isRtl, setIsRtl] = React.useState(false);
  const [value, setValue] = React.useState("initial value");
  React.useLayoutEffect(() => {
    document.body.setAttribute("dir", isRtl ? "rtl" : "ltr");
  }, [isRtl]);
  return (
    <ThemeProvider theme={isRtl ? rtlTheme : ltrTheme}>
      <CssBaseline />
      <Box m={2}>
        <TextField
          variant="outlined"
          value={value}
          onChange={(event) => setValue(event.target.value)}
          label={isRtl ? "بريد الكتروني او هاتف" : "Email or Phone"}
        />
        <br />
        <br />
        Current Direction: {isRtl ? "rtl" : "ltr"}
        <br />
        <Button onClick={() => setIsRtl(!isRtl)}>Toggle direction</Button>
      </Box>
    </ThemeProvider>
  );
}
export default function App() {
  return (
    <StylesProvider jss={jss}>
      <AppContent />
    </StylesProvider>
  );
}

下面是使用 Emotion 的 v5 的等效示例。

import React from "react";
import rtlPlugin from "stylis-plugin-rtl";
import { CacheProvider } from "@emotion/react";
import createCache from "@emotion/cache";
import { ThemeProvider, createTheme } from "@mui/material/styles";
import CssBaseline from "@mui/material/CssBaseline";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import { prefixer } from "stylis";

const cacheLtr = createCache({
  key: "muiltr"
});

const cacheRtl = createCache({
  key: "muirtl",
  // prefixer is the only stylis plugin by default, so when
  // overriding the plugins you need to include it explicitly
  // if you want to retain the auto-prefixing behavior.
  stylisPlugins: [prefixer, rtlPlugin]
});

const ltrTheme = createTheme({ direction: "ltr" });
const rtlTheme = createTheme({ direction: "rtl" });

export default function App() {
  const [isRtl, setIsRtl] = React.useState(false);
  const [value, setValue] = React.useState("initial value");
  React.useLayoutEffect(() => {
    document.body.setAttribute("dir", isRtl ? "rtl" : "ltr");
  }, [isRtl]);
  return (
    <CacheProvider value={isRtl ? cacheRtl : cacheLtr}>
      <ThemeProvider theme={isRtl ? rtlTheme : ltrTheme}>
        <CssBaseline />
        <Box m={2}>
          <TextField
            value={value}
            onChange={(event) => setValue(event.target.value)}
            label={isRtl ? "بريد الكتروني او هاتف" : "Email or Phone"}
          />
          <br />
          <br />
          Current Direction: {isRtl ? "rtl" : "ltr"}
          <br />
          <Button onClick={() => setIsRtl(!isRtl)}>Toggle direction</Button>
        </Box>
      </ThemeProvider>
    </CacheProvider>
  );
}

另外,我后面有一个答案讨论了翻转图标:当我更改为 RTL 时,material-ui 图标不会翻转 https://stackoverflow.com/questions/64307165/material-ui-icons-wont-flip-when-i-change-to-rtl/64307950#64307950.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Material-Ui TextField 不受 RTL 方向影响 的相关文章

随机推荐

  • primefaces 日历:如何动态设置 Mindate

    我有两个 primefaces 日历控件 我希望当我从第一个日历中选择日期时 下一个日历注意日期应该从第一个日历的选定日期开始 例如 我选择了7 5 2013那么下一个日历应该禁用之前的所有日期8 5 2013这是我到目前为止所尝试过的 但
  • 匹配一行中的第 n 个单词

    在我使用的应用程序中 我无法选择比赛组 1 我可以使用的结果是正则表达式的完整匹配 但我需要第 5 个单词 jumps 作为匹配结果 而不是完整的匹配项 The Quick Brown Fox Jumps 4 The quick brown
  • SQL where field in vs. where field = 带有多个 or ?

    就性能而言 使用哪一个更好 关于可读性 可理解性 关于公认的标准 SELECT FROM Wherever WHERE Greeting IN hello hi hey OR SELECT FROM Wherever WHERE Greet
  • ios 上的外部键盘选项卡事件

    我的 iPad 应用程序屏幕之一有多个文本字段 在这几个文本字段上 会生成用于用户输入操作 决策 预填充信息等的弹出窗口 当使用默认的 ipad 键盘时 它工作正常 但是当我们尝试使用带有 Tab 键的外部键盘时 我得到了多个文本字段应该开
  • 用于闪亮 Python 3D 曲面图的 Phong 着色

    我正在尝试在 Python 中使用镜面着色创建美观的 3D 绘图 到目前为止 我已尝试将 Matplotlib 与 Mayavi 的 3D 轴和曲面图一起使用 例如来自 Mayavi surf 示例网页 结果看起来不错 在 Mayavi 中
  • 自动同步 Subversion 存储库和 Git 存储库

    我的项目在网络文件系统上有一个 Subversion 存储库 新团队希望使用 Git 访问它 并能够提交它并从中获取更新 我的想法是创建一个新的裸git svn在同一网络文件系统上克隆 Subversion 存储库 并确保这两个存储库始终彼
  • 如何更改附加到导航视图的子菜单的文本和图标的颜色?

    我试图弄清楚如何更改实际附加到导航视图的子菜单项的颜色 以下代码实际上来自 android studio 中可用的导航抽屉的默认模板 活动 主 抽屉 xml menu menu
  • 哪里有 Firefox 3.5 中位置感知浏览的 Javascript 代码示例?

    有谁知道我在哪里可以找到 Firefox 3 5 的新位置感知功能的一些 javascript 代码示例 Try hacks mozilla org http hacks mozilla org 2009 06 geolocation an
  • 检查两次之间的时间[重复]

    这个问题在这里已经有答案了 我只想检查当前时间是否在 2 次之间 到目前为止 我浏览了多个脚本 但所有脚本都包含日期 或者只是太困难 或者脚本只计算完整小时 如 6 或 7 而我需要检查小时和分钟 我很感激您的帮助 我想要的脚本设置是 be
  • 在 Elastic Beanstalk 上运行 npm install 时出现问题

    情况 我有一个 Laravel 5 4 应用程序 它使用 npm bower 和 gulp 作为前端 我已在部署时成功配置了所有内容 但是npm install or npm install production 在我的情况下是相同的 命令
  • jwt.decode() 收到意外的关键字参数“verify”

    我可以使用路由 api token 生成令牌 但之后无法使用它 之前一切正常 但现在我在 django Rest Framework 中遇到此错误 我不知道为什么 File home mathieu local share virtuale
  • Android - Intent.setType() 参数

    有谁知道该方法的所有可用参数 像 图像 或 文件 我在官方文档中没有找到该列表的线索 具体来说 我需要发送联系人 vcf 文件的意图 但输入 file vcf 并没有显示通过短信发送选项 sendIntent setData Uri par
  • 在php中读取mp3流并回显给客户端

    我想要实现的是一个页面 当客户端连接时 该页面不断地从本地ice cast服务器读取 http 127 0 0 1 8000 stream mp3 并将流回显给客户端 从那里 客户端可以在基本音频标签中播放它
  • 在 Ruby 语言的一个 if 语句中使用多个条件

    我用 Ruby 写了这样的东西 if a max a 0 brand b 0 elsif a max a 1 brand b 1 elsif a max a 2 brand b 2 elsif a max a 3 brand b 3 end
  • 使用 JSDoc 记录成员函数

    我有这样的事情 Diese Klasse bla bla constructor my namespace ClassA function type This function does something this doSomething
  • 正确实施带有回发的 Web 部件?

    我想做的是创建一个 Web 部件 它有一个文本框 您可以在其中设置 Web 部件上的文字 h2 的值 以及一个回发的 保存 按钮 然后相应地设置文字 这有一个巨大的警告 当页面在回发后加载时 文字并没有改变 但是 如果我记录文字中实际设置的
  • 当日期采用以下格式时,将 BIGQUERY 中的字符串转换为日期:M/D/YYYY

    我有一个日期字符串 格式为 M D YYYY 即 1 1 2018 12 31 2018 我收到无效日期错误 它显示 2 18 2018 作为无效日期 有任何想法吗 以下是 BigQuery 标准 SQL 的示例 standardSQL W
  • 从 C 执行二进制机器代码

    下列的this http www muppetlabs com breadbox software tiny teensy html我已经成功地生成了大小为 528 字节的 a out 当 gcc main c 最初给了我 8539 字节的
  • 使用日期时间 POSIXlt 创建 R data.table 时出错

    使用日期时间列创建 data table 时出现问题 gt mdt lt data table id 1 3 d strptime c 06 02 36 06 02 48 07 03 12 H M S gt class mdt 1 data
  • Material-Ui TextField 不受 RTL 方向影响

    我在我的 React 项目中使用 Material Ui 我按照中的步骤操作文档 https material ui com guides right to left opting out of rtl transformation允许 R