【问题标题】:Architecture example for a multi-language application using React, React Redux or React Context, and Material UI使用 React、React Redux 或 React Context 和 Material UI 的多语言应用程序的架构示例
【发布时间】:2020-09-27 02:23:45
【问题描述】:

我正在使用 React 和 Material UI 的应用程序工作。应用程序需要根据语言环境值翻译用户界面。我需要提供 5 种语言的设施。我想达到与Material UI documentation page 类似的响应水平。

I noticed that for the base language, which is English, the routes do not include a language segment on the URL path, but when a language other than English is selected, the URL has a language segment.例如,英文的本地化页面 URL 是 https://material-ui.com/guides/localization/,而法语的同一页面是 https://material-ui.com/fr/guides/localization/。

对架构模式或示例代码的任何引用将不胜感激。

【问题讨论】:

    标签: reactjs react-redux internationalization material-ui material-design


    【解决方案1】:

    它有什么好处

    • 以后如果需要更改路径名,只需更改 PATHS
    • 您可以在配置文件 genericRoutes 中添加组件
    • 对于本地化path={`/:language?/${path}`},您可以这样使用。
    import { Route } from 'react-router-dom';
    
    const PATHS = {
        SIGN_UP: '/sign-up',
        CONFIRMATION: '/confirmation'
    }
    
    const genericRoutes = [
        {
          path: PATHS.SIGN_UP,
          component: SignUp,
        },
        {
          path: PATHS.CONFIRMATION,
          component: Confirmation,
        },
    ]
    
    const GenericRoute = (props) => <Route {...props} />;
    
    const Routes = () => {
        return (
            <Switch>
                {genericRoutes.map(({ path, component, exact = true }, key) => (
                    <GenericRoute
                    key={key}
                    exact={exact}
                    path={`/:language?/${path}`}
                    component={component}
                    />
                ))}
            </Switch>
        )
    }
    
    
    

    【讨论】:

      【解决方案2】:

      这不是您想要的,但我是否也建议您给i18next 看看?它在选择显示语言时为您提供了很大的灵活性,甚至可以检测用户浏览器的语言。您还可以选择传递路径中的语言,类似于其他人的建议。配置它很简单,您可以插入值,拥有备用语言,仅举几例它提供的功能。

      附: Here 是 Material UI 的表现方式,如果你也在追求同样的目标。

      【讨论】:

        【解决方案3】:

        您似乎正在寻找这样一条路线:

        <Route path="/:language?/guides/localization">
          {props => <div>{Object.entries(props.match.params).map(p => `${p[0]}=${p[1]}`).join(" ")}</div> }
        </Route>
        

        如果props.match.params.language 是undefined,则使用默认值(即英文)。

        【讨论】:

        • 感谢您的回复。我正在为支持 UI 的不同语言的应用程序寻找更多的架构设计。如何将所有内容放在一起。
        【解决方案4】:

        在我当前的项目中,我使用的是i18next as a hook,它带有钩子名称useTranslation。在上面的链接中,我附上了一步一步的指南来做同样的事情。在此帮助下,我们支持 28 种语言的翻译,这对我们来说非常有效。

        我希望它也能帮助你。 :)

        【讨论】:

          猜你喜欢
          • 2016-01-29
          • 2019-06-14
          • 2020-12-15
          • 2018-09-26
          • 2016-06-11
          • 2021-06-25
          • 2019-04-18
          • 2016-09-20
          相关资源
          最近更新 更多