Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

100 行代码给你app国际化 #14

Open
hulin32 opened this issue Jun 13, 2018 · 0 comments
Open

100 行代码给你app国际化 #14

hulin32 opened this issue Jun 13, 2018 · 0 comments
Labels

Comments

@hulin32
Copy link
Owner

hulin32 commented Jun 13, 2018

做网站的时候现在经常都会有国际化的要求,社区里面有很多相关的包可以用,最多被用的估计是react-intl,当然我们公司也不例外了,但是当我看着它出现在代码里面的时候真是不自在,一堆的api,需要很多的配置,而且很多其实平时根本就用不到,想了想根据最近react的apiContext实现一个挺容易的,于是我自己动手试了一下,然后有了react-i18context

做这个包的初衷是为了保持简单,所以接口就4个,但是我觉得大多数的国际化都已经够用了。

1.注入翻译文件

// 在app最外层套一个,messages是翻译的一个数组对象, 然后初始化要使用的语言
<IntlProvider messages={messages} locale="en">
    <App />
</IntlProvider>

2. 使用翻译的字段

// id 是你翻译文件里语言对象的key
<FormatMsg id="test" />
// 如果你的源文件的test是test: 'hello {name}',通过inject参数,test的值最终会变成‘hello inject'
<FormatMsg id="test"  inject={{ name: 'inject' }} />

3. 切换语言

// locale的值根据你注入翻译文件时对象的key来定
<LocaleSet locale={lang}>
  <button>change language</button>
</LocaleSet>

4. 手动更换语言

// FooComponent 的props里就会注入changeLan方法,然后你就可以自己选择调用的时机了。
InjectIntlLangWrapper(FooComponent)

在线demo
npm包
代码react-i18context,欢迎代码骚扰

@hulin32 hulin32 added the React label Jun 13, 2018
@hulin32 hulin32 changed the title 70 行代码给你app国际化 100 行代码给你app国际化 Jun 17, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant