如果有一个非常明显的解决方案,我提前道歉,但我对React.js非常陌生。
我正在使用google-translate api构建一个简单的翻译器,component.The文本输入存储在状态中并由translateInput()使用,然后我想用翻译后的文本设置状态。不幸的是,我不能,但是我可以console.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)
})
}发布于 2019-09-14 09:31:02
您正在使用的函数的上下文不能通过this关键字访问组件,因为您正在使用function关键字创建函数作用域。使用箭头函数应该可以做到这一点:
translateInput = () => {
googleTranslate.translate([this.state.input],"en", "de",
(err, translations) => {
this.setState({translatedInput:translations.translatedText})
console.log(translations.translatedText)
})
}https://stackoverflow.com/questions/57931770
复制相似问题