【问题标题】:Getting results from Yandex translate从 Yandex 翻译中获取结果
【发布时间】:2019-12-14 13:50:56
【问题描述】:

这是一个愚蠢的问题,但我正在使用 Yandex API 通过将西班牙语单词/短语粘贴到函数中来将单词从西班牙语翻译成英语。但是,我不知道如何从函数中实际返回翻译!如何让我的 changeString 方法返回 res.text[0]?

import React, { Component } from "react";

class Display extends Component {
  render() {
    return (
      <div>
        <button> {this.changeString(this.props.translation)} </button>
      </div>
    );
  }

  changeString = spanishText => {
    var output = null;
    var translate = require("yandex-translate")(
      "API KEY"
    );

    translate.translate(spanishText, { to: "en" }, function(err, res) {
      console.log(res.text)
    });
  };
}

export default Display;

【问题讨论】:

    标签: reactjs yandex


    【解决方案1】:

    您可以将其设置为状态并对其进行更新以触发重新渲染。像下面这样

    import React, { Component } from "react";
    
    class Display extends Component {
      constructor(props) {
        super(props);
        this.state = { theWord: '' };
      }
    
      componentDidMount() {
        var output = null;
        var translate = require("yandex-translate")(
          "API KEY"
        );
    
        translate.translate('spanishText',{ to: "en" }, (err, res) => {
          this.setState({theWord: res});
        });
      }
    
      render() {
        return (
          <div>
            <button> {this.state.theWord} </button>
          </div>
        );
      }
    }
    
    export default Display;
    
    

    【讨论】:

    • 我试过这个,它抱怨它“无法读取未定义的属性'setState'”
    • @Perplexityy 将其更改为用于自动绑定的箭头函数。现在应该可以了
    • 尝试改成componentDidMount = () => { 但还是同样的错误!
    • @Perplexityy 不是那部分。 translate.translate 函数的回调。再次检查我的代码,我更新了它
    • 好的,但现在它不再翻译我的道具,它只是翻译“spanishText”
    猜你喜欢
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多