如何在 React 中使用 google 翻译 api

How to use google translation api with react

我查看了网站上的文档,但没有关于如何在 React 项目中使用 google 翻译 api 的示例。有谁知道如何集成它以便我可以对 API 进行简单的翻译调用? 谢谢

因此,在 Gregory 的帮助下实现 google translate 仅使用 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);
});

在这里你可以用响应做一些事情。

希望这对某人有所帮助,感谢 Gregory 提供的最明显的帮助:)

我用 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;

只是更正 url 中的拼写错误。

let url = `https://translation.googleapis.com/language/translate/v2?key=${API_KEY}`;
url += '&q=' + encodeURI(text);
url += `&source=${fromLang}`;
url += `&target=${toLang}`;

自动使用用户语言:

    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(/(&quot\;)/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>
          </>
        )
      }
     }
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const Convert = ({ text, language }) => {
  const [convertedText, setConvertedText] = useState('');

  useEffect(() => {
    const response = axios
      .post(
        'https://translation.googleapis.com/language/translate/v2',
        {},
        {
          params: {
            q: text,
            target: language,
            key: 'AIzaSyCHUCmpR7cT_yDFHC98CZJy2LTms-IwDlM'
          }
        }
      )
      .then((response) => {
        setConvertedText(response.data.data.translations[0].translatedText);
      })
      .catch((err) => {
        console.log('rest api error', err);
      });
  }, [text, language]);

  return <div>{convertedText}</div>;
};

export default Convert;


params 对象中的 'q' 参数是我们要翻译的文本,'target' 是我们要将文本翻译成的语言。