我已经浏览了网站上的文档,但没有示例如何在 React 项目中使用谷歌翻译 API。有谁知道如何集成它,以便我可以对 API 进行简单的翻译调用?谢谢
如何在react中使用谷歌翻译 API
IT技术
reactjs
google-translate
2021-05-23 09:36:13
4个回答
因此,在 Gregory 的帮助下,谷歌翻译只使用了一个 REST api,我通过使用 fetch 进行了一个简单的调用来实现这一点。如果其他人也尝试这样做,我将在此处添加一些代码:
let fromLang = 'en';
let toLang = 'no'' // translate to norwegian
let text = 'something to translate';
const API_KEY = [YOUR_API_KEY];
let url = `https://translation.googleapis.com/language/translate/v2?key=${API_KEY}`;
url += '&q=' + encodeURI(text);
url += `&source=${fromLang}`;
url += `&target=${toLang}`;
fetch(url, {
method: 'GET',
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
})
.then(res => res.json())
.then((response) => {
console.log("response from google: ", response);
})
.catch(error => {
console.log("There was an error with the translation request: ", error);
});
在这里,您可以使用响应做一些事情。
希望这可以帮助某人并感谢格雷戈里最明显的帮助:)
自动使用用户语言:
import React from 'react'
export default class Translate extends React.Component{
constructor(props){
super(props)
this.state={
greeting:'I say: "Hello, you all!"',
greeting_in_user_language: null
}
this.userLanguage = navigator.language.slice(0,2)
this.API_KEY = 'YOUR_API_KEY'
this.URL = `https://translation.googleapis.com/language/translate/v2?key=${this.API_KEY}&source=en`
this.URL += `&target=${this.userLanguage}`
}
componentWillMount() {
this.translate( 'greeting_in_user_language', '&q=' + encodeURI(this.state.greeting))
}
translate = (key,string_to_translate) => {
fetch(this.URL+string_to_translate)
.then(res => res.json())
.then(
( res ) => {
let text = res.data.translations[0].translatedText.replace(/("\;)/g,"\"")
this.setState({[key]:text})
}
) .catch(
( error ) => {
console.log("There was an error: ", error);
}
)
}
render() {
return(
<>
<section className="page">
<p>{
this.state.greeting_in_user_language ?
this.state.greeting_in_user_language :
this.state.greeting
}</p>
</section>
</>
)
}
}
我用 nodeJs 做了这个,在阅读了你的问题后,我通过我的本地主机做了一个请求,希望这会有所帮助。
NodeJs index.js
route.post('/', (req, res) => {
var q = req.body.q;
console.log(q);
var options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
form:
{ key: process.env.TRANSLATE,
q: q,
target: 'en' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
res.send(body);
});
})
ReactJS App.js
class App extends Component {
constructor(props){
super(props);
this.state = {
value: '',
translated: '...'
}
this.translate=this.translate.bind(this);
}
translate(){
axios.post('http://localhost:9000/translate',{q:this.state.value})
.then(data => {
this.setState({translated: data.data.data.translations[0].translatedText})
console.log(data.data.data.translations[0].translatedText)
}).catch(err => {
console.log('error')
})
}
render() {
return (
<div>
<input
value={this.state.value}
onChange={(e)=>this.setState({value: e.target.value})}
type="text"/>
<button onClick={this.translate}>Submit</button>
<h1>{this.state.translated}</h1>
</div>
);
}
}
export default App;
只是更正网址中的拼写错误。
let url = `https://translation.googleapis.com/language/translate/v2?key=${API_KEY}`;
url += '&q=' + encodeURI(text);
url += `&source=${fromLang}`;
url += `&target=${toLang}`;