如果有一个超级明显的解决方案,我提前道歉,但我对 React.js 很陌生。
我正在使用谷歌翻译 API 来构建一个简单的翻译器组件。文本输入存储在状态中并由 translateInput(( 使用,然后我想用翻译后的文本设置状态。不幸的是,我不能,但是我可以控制台.log googleTranslate函数返回的值。为什么会这样?我必须以某种方式绑定回调函数吗?
谢谢!
import React, { Component } from "react";
import { googleTranslate } from '../utils/googleTranslate';
class Translator extends Component {
constructor(){
super();
this.state = {
input:'',
translatedInput: '',
}
}
handleTextInput = e => {
this.setState({input:e.target.value})
}
translateInput = () => {
googleTranslate.translate([this.state.input],"en", "de",
function (err, translations){
//this.setState({translatedInput:translations.translatedText})
//TypeError: Cannot read property 'setState' of undefined
console.log(translations.translatedText)
})
}
您正在使用的函数的上下文无法通过this
关键字访问组件,因为您正在使用function
关键字创建函数作用域。 使用箭头函数应该可以解决问题:
translateInput = () => {
googleTranslate.translate([this.state.input],"en", "de",
(err, translations) => {
this.setState({translatedInput:translations.translatedText})
console.log(translations.translatedText)
})
}