通过大量研究,我知道国际化/本地化是 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 注入需要其中一个字符串的每个组件的开销。是否有其他原因不首选此解决方案?