const args = getUrlParam();
const lang = args.lang || 'zh_CN';
const langFile = require(`./components/locale-provider/${lang}`).default;
<LocaleProvider locale={langFile}> <Router history={history} routes={routes} /> </LocaleProvider> 複製代碼
//zh_CN.js
export default {
locale: 'zh-cn',
global: {},
multi: {
text: '你好',
}
}
//en_US.js
export default {
locale: 'en-us',
// 全局: 好比 xx小時xx分鐘 該怎麼轉成英文
global: {},
multi: {
text: 'hello',
}
}
複製代碼
import React, { Component } from 'react';
import { injectLocale } from '@/components/locale-provider';
@injectLocale()
export default class MultiLang extends Component {
render() {
const { locale: { multi } } = this.props;
return <div className="multi">{multi.text}</div>;
}
}
// 等價於
//export default injectLocale()(MultiLang);
複製代碼
三種實現方式:javascript
- 組合props
- 繼承
- 以函數做爲children
// locale-provider/index.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class LocaleProvider extends Component {
getChildContext() {
return {
locale: { ...this.props.locale },
};
}
render() {
return React.Children.only(this.props.children);
}
}
LocaleProvider.propTypes = {
locale: PropTypes.object,
};
LocaleProvider.defaultProps = {
locale: PropTypes.object,
};
LocaleProvider.childContextTypes = {
locale: PropTypes.object,
};
export { default as injectLocale } from './injectLocale';
複製代碼
import { Component, createElement } from 'react';
import PropTypes from 'prop-types';
import hoistStatics from 'hoist-non-react-statics';
export default function injectLocale(defaultLocale = {}) {
return function wrapWithLocale(WrappedComponent) {
class Inject extends Component {
static contextTypes = {
locale: PropTypes.object,
};
getLocale = () => {
const { locale } = this.context;
const localeFromContext = locale;
return {
...localeFromContext,
...defaultLocale,
};
}
addLocaleProps = () => ({ ...this.props, locale: this.getLocale() })
render() {
return createElement(WrappedComponent, this.addLocaleProps());
}
}
return hoistStatics(Inject, WrappedComponent);
};
}
複製代碼
什麼是裝飾器java
@testable
class A {}
function testable(target) {
target.isTestable = true;
}
MyTestableClass.isTestable // true
// 等同於
class A {}
A = testable(A) || A;
複製代碼
class Person {
@readonly
name() { return `${this.first} ${this.last}` }
}
function readonly(target, name, descriptor){
// descriptor對象原來的值以下
// {
// value: specifiedFunction,
// enumerable: false,
// configurable: true,
// writable: true
// };
descriptor.writable = false;
return descriptor;
}
readonly(Person.prototype, 'name', descriptor);
// 相似於
Object.defineProperty(Person.prototype, 'name', descriptor);
複製代碼
Tip: 這代碼是幾個月前寫的, 同時這是我第一次發表文章, 你們給新人一點鼓勵哈~react