开源软件名称(OpenSource Name):eugene-manuilov/react-gettext开源软件地址(OpenSource Url):https://github.com/eugene-manuilov/react-gettext开源编程语言(OpenSource Language):JavaScript 100.0%开源软件介绍(OpenSource Introduction):react-gettext 1.0.2A tiny React library that helps to implement internalization in your application using gettext functions. It uses React Context API to expose gettext functions to children components. Instalation
UsageTo use this library in your application, you need to do a few simple steps:
Let's take a closer look at each step. First of all, you to create translation catalogs and prepare plural form functions for every language that you are going to use. Each language needs one catalog and one plural form function. The translation catalog is an object that contains key/value pairs where keys are original singular messages and values are translations. If you have a message that can have plural forms, the value for it should be an array with translations where each translation corresponds to appropriate plural form. Finally, if you want to use a context with your messages, then it should be prepended to the message itself and separated by using {
"Hello world!": "¡Hola Mundo!", // regular message
"article": ["artículo", "artículos"], // plural version
"Logo link\u0004Homepage": "Página principal", // single message with "Logo link" contex
"Search results count\u0004article": ["artículo", "artículos"], // plural version with "Search results count" context
} The plural form function is a function that determines the number of a plural form that should be used for a particular translation. For English, the plural form is function getPluralForm(n) {
return n != 1 ? 1 : 0;
} The next step is to pass translations and plural form function for the current language to the import React, { Component } from 'react';
import { TextdomainContext, buildTextdomain } from 'react-gettext';
class MyApp extends Component {
constructor(props) {
super(props);
this.state = { textdomain: buildTextdomain(...) };
}
render() {
return (
<div>
<TextdomainContext.Provider value={this.state.textdomain}>
<ComponentA />
...
</TextdomainContext>
</div>
);
}
}
Finally, the last step is to update your descendant components to consume these context APIs. Import import React, { Component } from 'react';
import { TextdomainContext } from 'react-gettext';
class ComponentA extends Component {
render() {
const { gettext, ngettext, xgettext, nxgettext } = this.context;
return (
<div>...</div>
);
}
}
ComponentA.contextType = TextdomainContext; An exampleLet's assume you have following React application: // app.js
import React, { Component } from 'react';
import Header from './Header';
import Footer from './Footer';
export default class App extends Component {
render() {
return (
<div id="app">
<Header />
...
<Footer />
</div>
);
}
} // Header.js
import React, { Component } from 'react';
export default class Header extends Component {
render() {
return (
<h1>Welcome to my application!</h1>
);
}
} To make it translatable, you need to update your // app.js
import React, { Component } from 'react';
+ import { TextdomainContext, buildTextdomain } from 'react-gettext';
import Header from './Header';
import Footer from './Footer';
export default class App extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ textdomain: buildTextdomain(
+ {
+ 'Welcome to my application!': 'Bienvenido a mi aplicación!',
+ // ...
+ },
+ n => n != 1
+ ),
+ };
+ }
render() {
return (
<div id="app">
+ <TextdomainContext.Provider value={this.state.textdomain}>
<Header />
...
<Footer />
+ </TextdomainContext.Provider>
</div>
);
}
} After doing it you can start using // Header.js
import React, { Component } from 'react';
+ import { TextdomainContext } from 'react-gettext';
export default class Header extends Component {
render() {
+ const { gettext } = this.context;
return (
- <h1>Welcome to my application!</h1>
+ <h1>{gettext('Welcome to my application!')}</h1>
);
}
}
+ Header.contextType = TextdomainContext; Check a sample application to see how it works. DocumentationbuildTextdomain(translations, pluralForm)Builds gettext APIs for TextdomainContext provider that will work with provided translations.
const api = buildTextdomain( { ... }, n => n == 1 ? 0 : 1 );
// or
const api = buildTextdomain( { ... }, 'n == 1 ? 0 : 1' ); gettext(message)The function to translate a string. Accepts original message and returns translation if it exists, otherwise original message.
Example: // somewhere in your jsx component
this.context.gettext('Some text'); ngettext(singular, plural, n)The function to translate plural string. Accepts singular and plural messages along with a number to calculate plural form against. Returns translated message based on plural form if it exists, otherwise original message based on n value.
Example: // somewhere in your jsx component
this.context.ngettext('day ago', 'days ago', numberOfDays); xgettext(message, context)The function to translate a string based on a specific context. Accepts a message to translate and a translation context string. Returns translated message if it exists, otherwise original string.
Example: // somewhere in your jsx component
this.context.xgettext('some text', 'context where this message is used'); nxgettext(singular, plural, n, context)The function to translate plural string based on a specific context. Accepts singular and plural messages along with a number to calculate plural form against and context string. Returns translated message based on plural form if it exists, otherwise original message based on n value.
Example: // somewhere in your jsx component
this.context.nxgettext('day ago', 'days ago', numberOfDays, 'Article publish date'); Legacy APIThe initial version of this library had been created when React used the legacy version of Context APIs, thus it played a keystone role in the main approach of how to use this library at that time. However, in the late March of 2018, React 16.3 was released and that API became deprecated, so do the main approach used in this library. The proper way to use this library is described in the Usage section, this section contains legacy API that will be removed in next versions of the library. We don't encourage you to use it in a new project. withGettext(translations, pluralForms, options)Higher-order function which is exported by default from
Example: const translations = {
'Some text': 'Some translated text',
...
};
const pluralForms = '(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)'; // 3 plural forms for Russian, Belarusian, Bosnian, Croatian, Serbian, Ukrainian, etc.
const HOC = withGettext(translations, pluralForms)(App); function getTranslations() {
return {
'Some text': 'Some translated text',
...
};
}
function getPluralForms(n) {
return n > 1 ? 1 : 0;
}
const HOC = withGettext(getTranslations, getPluralForms)(App); As an alternative you can pass translations and plural form as properties to higher-order-component, like this: function getTranslations() {
return {
'Some text': 'Some translated text',
...
};
}
function getPluralForms(n) {
return n > 1 ? 1 : 0;
}
const HOC = withGettext()(App);
...
ReactDOM.render(<HOC translations={getTranslations} plural={getPluralForms}>...</HOC>, ...); One more alternative is to not create HOC, but use Textdomain component directly. You can import it using PoeditIf you want to use Poedit application to translate your messages, then use the following keywords to properly extract static copy from your javascript files:
Here is an example of a POT file that you can use as a starting point:
If you prefer using npm scripts, then you can add the following command to your
ContributeWant to help or have a suggestion? Open a new ticket and we can discuss it or submit pull request. Please, make sure you run LicenseMIT |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论