3

通过大量研究,我知道国际化/本地化是 React上下文功能的少数合法用例之一。但是我的问题是关于是否真的需要使用上下文。将要国际化的组件包装在提供本地化字符串作为道具的高阶组件中不是同样有效吗?例如,对于支持英语和西班牙语的应用程序:

// WithLocale.js
import React from 'react';

import en from './locales/en-US.json';
import es from './locales/es-ES.json';

const locales = {'en-US': en, 'es-ES': es};

let currentLocale = (navigator.languages && navigator.languages[0])
    || navigator.language
    || navigator.userLanguage
    || 'en-US';

const WithLocale = (WrappedComponent) => {
    return (props) => {
            const locale = { strings: locales[currentLocale] };
            return <WrappedComponent {...props} locale={locale} />
    }
};

export default WithLocale;

使用本地化 JSON,例如:

// en.json
{
  "header": "My App",
  "description": "This is an internationalizated app in React",
}

以及如何在组件中使用它的一个非常基本的示例:

import React from 'react';
import PropTypes from 'prop-types';
import WithLocale from './WithLocale';

const SubComponent = (props) => (
        <div>
            <p className="App-intro">
                {props.locale.strings.description}
            </p>
        </div>
);

SubComponent.propTypes = {
    locale: PropTypes.object
};

export default WithLocale(SubComponent);

我能想到的主要问题是将潜在的大型 JSON 注入需要其中一个字符串的每个组件的开销。是否有其他原因不首选此解决方案?

4

1 回答 1

1

使用大型本地化结构props作为Component. 因为对象不是按值传递的,而是对对象的引用被复制。所以没有什么需要担心的问题。

真正的问题是,当您不使用时,context您必须将本地化从根一直传递Component到最底层。如果您的中间人Components不关心本地化,他们仍然必须接受本地化道具并进一步传递它们。

这就是为什么人们使用context: 来让中间Components层完全不知道一些Components在层次结构中较低的东西所使用的东西。

更新。尽管在切换语言环境时WithLocale强制重绘存在问题,但您的解决方案将起作用。Components您必须currentLocale在两个地方进行更新:内部WithLocale.js和根目录Component。除此之外,与使用context.

于 2017-08-28T04:56:44.070 回答