Material-Ui TextField 不受 RTL 方向影响

Ala*_*bil 2 reactjs material-ui

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

我按照文档中的步骤在我的项目中允许 RTL 并且一切正常!

除了 TextField 组件

LTR方向:

在此处输入图片说明

RTL方向

在此处输入图片说明

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

App.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);
Run Code Online (Sandbox Code Playgroud)

我的表单组件

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>
    </>
     );
  };
Run Code Online (Sandbox Code Playgroud)

我的 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"
        }
    },

}
Run Code Online (Sandbox Code Playgroud)

);

导出默认主题;

有什么建议可以制作标签 RTL 吗?

Rya*_*ell 13

您链接到的文档包含 rtl 支持的三个步骤:

  1. dirbody元素上设置属性。

在我下面的示例中,这是由以下处理的:

  React.useLayoutEffect(() => {
    document.body.setAttribute("dir", isRtl ? "rtl" : "ltr");
  }, [isRtl]);
Run Code Online (Sandbox Code Playgroud)
  1. direction在主题中设置。

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

const ltrTheme = createMuiTheme({ direction: "ltr" });
const rtlTheme = createMuiTheme({ direction: "rtl" });
...
<ThemeProvider theme={isRtl ? rtlTheme : ltrTheme}>
...
</ThemeProvider>
Run Code Online (Sandbox Code Playgroud)
  1. 安装 jss-rtl 插件。

出于性能原因,避免重新渲染很重要StylesProvider,因此这不应该处于状态可以更改并因此触发重新渲染的组件中。在自己的应用程序,我有StylesProvider我的元index.js文件作为来电中的第一个元素反应-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>
  );
}
Run Code Online (Sandbox Code Playgroud)

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

import React from "react";
import { create } from "jss";
import rtl from "jss-rtl";
import {
  StylesProvider,
  jssPreset,
  ThemeProvider,
  createMuiTheme
} 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 = createMuiTheme({ direction: "ltr" });
const rtlTheme = createMuiTheme({ direction: "rtl" });

function AppContent() {
  const [isRtl, setIsRtl] = React.useState(false);
  React.useLayoutEffect(() => {
    document.body.setAttribute("dir", isRtl ? "rtl" : "ltr");
  }, [isRtl]);
  return (
    <ThemeProvider theme={isRtl ? rtlTheme : ltrTheme}>
      <CssBaseline />
      <Box m={2}>
        <TextField 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>
  );
}
Run Code Online (Sandbox Code Playgroud)

编辑 rtl 示例

另外,我后面有一个讨论翻转图标的答案:material-ui 图标在我更改为 RTL 时不会翻转