我不知道如何用我的google-translate API显示我正在翻译的单词...我想要显示从函数newText翻译过来的单词,以便显示在我调用该函数的文本标记中。(要翻译的词也来自TextInput的‘要翻译的词’。
const Main = ({ navigation }) => {
let apiKey = "AIzaasdfasdfasdfasdfasdfsdc";
let googleTranslate = require("google-translate")(apiKey);
const [text, setText] = useState("");
const newText = () => {
googleTranslate.translate(text, "es", function (err, translation) {
return translation.translatedText;
});
};
const onChangeText = (text) => setText(text);
return (
<View style={styles.screen}>
<ImageBackground
source={require("./assets/book.png")}
style={styles.backgroundImage}
>
<View style={styles.innerText}>
<Text style={{ fontSize: 20 }}>Welcome back Elisa, </Text>
<Text>let's practice that pronunciation...</Text>
<TextInput
placeholder="Word to translate"
style={styles.input}
onChangeText={onChangeText}
/>
</View>
<Text style={styles.output}>{newText()}</Text>
<View style={styles.button}>
<Button
title="START"
onPress={() => navigation.navigate("BACK_HOME")}
/>
</View>
</ImageBackground>
</View>
);
};发布于 2020-11-23 21:51:45
我已经将newText()转换为异步函数。
您可以使用onClick事件调用newText(),也可以使用onChange,因为我已经修改了下面的代码。
每当你的输入改变时,谷歌翻译就会被调用(这不是一个好主意,因为这意味着如果你输入100个字符,它就会翻译100次。)
我建议你添加一个像这样的按钮。
<button onClick={() => newText(text)}>Translate Me!</button>
const Main = ({ navigation }) => {
let apiKey = "AIzaasdfasdfasdfasdfasdfsdc";
let googleTranslate = require("google-translate")(apiKey);
const [text, setText] = useState("");
const [ translated, setTranslated ] = useState('');
const newText = async (toBeTranslated) => {
await googleTranslate.translate(toBeTranslated, "es", function (err, translation) {
setTranslated(translation.translatedText)
});
};
const onChangeText = (text) => {
setText(text);
//handle translation when text change.
newText(text);
}
return (
<View style={styles.screen}>
<ImageBackground
source={require("./assets/book.png")}
style={styles.backgroundImage}
>
<View style={styles.innerText}>
<Text style={{ fontSize: 20 }}>Welcome back Elisa, </Text>
<Text>let's practice that pronunciation...</Text>
<TextInput
placeholder="Word to translate"
style={styles.input}
onChangeText={onChangeText}
/>
</View>
<Text style={styles.output}>{translated}</Text>
<View style={styles.button}>
<Button
title="START"
onPress={() => navigation.navigate("BACK_HOME")}
/>
</View>
</ImageBackground>
</View>
);
};https://stackoverflow.com/questions/64969413
复制相似问题