开源软件名称(OpenSource Name):martinandert/react-translate-component开源软件地址(OpenSource Url):https://github.com/martinandert/react-translate-component开源编程语言(OpenSource Language):JavaScript 94.0%开源软件介绍(OpenSource Introduction):React Translate ComponentTranslate is a component for React that utilizes the Counterpart module and the Interpolate component to provide multi-lingual/localized text content. It allows switching locales without a page reload. InstallationInstall via npm: % npm install react-translate-component UsageHere is a quick-start tutorial to get you up and running with Translate. It's a step-by-step guide on how to build a simple app that uses the Translate component from scratch. We assume you have recent versions of Node.js and npm installed. First, let's create a new project: $ mkdir translate-example
$ cd translate-example
$ touch client.js
$ npm init # accept all defaults here Next, add the dependencies our little project requires: $ npm install react counterpart react-interpolate-component react-translate-component --save The We will put our application logic into 'use strict';
var counterpart = require('counterpart');
var React = require('react');
var ReactDOM = require('react-dom');
var Translate = require('react-translate-component'); This loads the localization library, React and our Translate component. Let's write our entry-point React component. Add the following code to the file: class MyApp extends React.Component {
render() {
return (
<html>
<head>
<meta charSet="utf-8" />
<title>React Translate Quick-Start</title>
<script src="/bundle.js" />
</head>
<body>
--> body content will be added soon <--
</body>
</html>
);
}
}
if (typeof window !== 'undefined') {
window.onload = function() {
ReactDOM.render(<MyApp />, document);
};
}
module.exports = MyApp; Now we have the basic HTML chrome for our tiny little app. Next, we will create a LocaleSwitcher component which will be used to, well, switch locales. Here is the code to append to class LocaleSwitcher extends React.Component {
handleChange(e) {
counterpart.setLocale(e.target.value);
}
render() {
return (
<p>
<span>Switch Locale:</span>
<select defaultValue={counterpart.getLocale()} onChange={this.handleChange}>
<option>en</option>
<option>de</option>
</select>
</p>
);
}
} For demonstration purposes, we don't bother and hard-code the available locales. Whenever the user selects a different locale from the drop-down, we correspondingly set the new drop-down's value as locale in the Counterpart library, which in turn triggers an event that our (soon to be integrated) Translate component listens to. As initially active value for the select element we specify Counterpart's current locale ("en" by default). Now add LocaleSwitcher as child of the empty body element of our MyApp component: <body>
<LocaleSwitcher />
</body> Next, we create a Greeter component that is going to display a localized message which will greet you: class Greeter extends React.Component {
render() {
return <Translate {...this.props} content="example.greeting" />;
}
} In the component's render function, we simply transfer all incoming props to Translate (the component this repo is all about). As Now add the new Greeter component to the body element, provide a <body>
<LocaleSwitcher />
<Greeter with={{ name: "Martin" }} component="h1" />
</body> The value of the All that's left to do is to add the actual translations. You do so by calling the counterpart.registerTranslations('en', {
example: {
greeting: 'Hello %(name)s! How are you today?'
}
});
counterpart.registerTranslations('de', {
example: {
greeting: 'Hallo, %(name)s! Wie geht\'s dir heute so?'
}
}); In the translations above we defined placeholders (in sprintf's named arguments syntax) which will be interpolated with the value of the That's it for the application logic. To eventually see this working in a browser, we need to create the server-side code that will be executed by Node.js. First, let's install some required dependencies and create a $ npm install express connect-browserify reactify node-jsx --save
$ touch server.js Now open up 'use strict';
var express = require('express');
var browserify = require('connect-browserify');
var reactify = require('reactify');
var React = require('react');
require('node-jsx').install();
var App = React.createFactory(require('./client'));
express()
.use('/bundle.js', browserify.serve({
entry: __dirname + '/client',
debug: true, watch: true,
transforms: [reactify]
}))
.get('/', function(req, res, next) {
res.send(React.renderToString(App()));
})
.listen(3000, function() {
console.log('Point your browser to http://localhost:3000');
}); Note that you shouldn't use this code in production as the Last but not least, start the application: $ node server.js It should tell you to point your browser to http://localhost:3000. There you will find the page greeting you. Observe that when switching locales the greeting message adjusts its text to the new locale without ever reloading the page or doing any ajax magic. Please take a look at this repo's Asynchronous Rendering on the Server-sideThe above example for To fix this, create a wrapper component (or extend your root component) and pass an instance of Counterpart as React context. Here's an example: var http = require('http');
var Translator = require('counterpart').Instance;
var React = require('react');
var ReactDOMServer = require('react-dom/server');
var Translate = require('react-translate-component');
var MyApp = require('./my/components/App');
var en = require('./my/locales/en');
var de = require('./my/locales/de');
class Wrapper extends React.Component {
getChildContext() {
return {
translator: this.props.translator
};
}
render() {
return <MyApp data={this.props.data} />;
}
}
Wrapper.childContextTypes = {
translator: Translate.translatorType
};
http.createServer(function(req, res) {
var queryData = url.parse(req.url, true).query;
var translator = new Translator();
translator.registerTranslations('en', en);
translator.registerTranslations('de', de);
translator.setLocale(req.locale || 'en');
doAsyncStuffHere(function(err, data) {
if (err) { return err; }
var html = ReactDOMServer.renderToString(
<Wrapper data={data} translator={translator} />
);
res.write(html);
});
}).listen(3000); An Advanced ExampleThe code for a more sophisticated example can be found in the repo's ContributingHere's a quick guide:
LicenceReleased under The MIT License. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论