【问题标题】:MUI5 TextField not affected with the RTL directionMUI5 TextField 不受 RTL 方向影响
【发布时间】:2022-01-02 10:01:51
【问题描述】:

我在我的应用程序中使用了 RTL 和 material-ui v4,它工作正常。

import React from "react"
import { create } from "jss"
import rtl from "jss-rtl"
import { StylesProvider, jssPreset } from "@mui/styles"

// @ts-ignore
const jss = create({ plugins: [...jssPreset().plugins, rtl()] })
// @ts-ignore
function RTL(props) {
  // @ts-ignore
  return <StylesProvider jss={jss}>{props.children}</StylesProvider>
}

export default RTL

现在,我升级到 MUI5。但 rtl 不受我的 textFields 和其他一些组件的影响。 我能做什么?

【问题讨论】:

    标签: reactjs material-ui direction


    【解决方案1】:

    基于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 插件 : 当使用emotionstyled-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>;
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 2022-01-21
      • 2021-08-29
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      相关资源
      最近更新 更多