import React from 'react';
import './Message.css';
import ReactEmoji from 'react-emoji';
var api = "**************";
var googleTranslate = require('google-translate')(api);
const Message = ({ message: { text, user }, name ,language}) => {
let isSentByCurrentUser = false;
const trimmedName = name.trim().toLowerCase();
if(user === trimmedName) {
isSentByCurrentUser = true;
}
var txt = googleTranslate.translate(text, 'es', function(err, translation) {
console.log("Spanish :>",translation.translatedText);
});
return (
isSentByCurrentUser
? (
<div className="messageContainer justifyEnd">
<p className="sentText pr-10">{trimmedName}</p>
<div className="messageBox backgroundBlue">
<p className="messageText colorWhite">{ReactEmoji.emojify(text)}</p>
</div>
</div>
)
: (
<div className="messageContainer justifyStart">
<div className="messageBox backgroundLight">
<p className="messageText colorDark">{ReactEmoji.emojify(txt)}</p>
</div>
<p className="sentText pl-10 ">{user}</p>
</div>
)
);
}
export default Message;
嗨。我正在尝试将“文本”翻译成西班牙文,并将其放入var“ txt”中,然后将其返回。但是我不知道如何避免goole translation api的回调。有什么想法吗?
与async
一起使用await
/ Promise
async function getTranslation(text){
return new Promise((resolve, reject) => {
googleTranslate.translate(text, 'es', function(err, translation) {
if(err){
reject(err);
}else{
resolve(translation);
}
});
});
}
比起您可以在异步函数中使用await
async function test(){
let result = await getTranslation('<text to translate>');
console.log(result);
}