繁体   English   中英

让ReactJS根据文本区域立即更改值?

[英]Getting ReactJS to instantly change value based on textarea?

我有一个文本区域,用户可以在其中输入位置。 然后,在onBlur中设置天气值,并根据用户键入的内容来更改结果。该代码将按预期工作。 但是,仅当用户将其触发两次时。

var Duck = React.createClass({
  getInitialState:function() {
    return {
      deesfault: 'Houston, Texas',
      setting: true,
      main: '',
    }
  },

  componentDidMount:function() {
    return this.callthebase();
  },

  callthebase: function() {
    var selfish = this;
    $.get('http://api.openweathermap.org/data/2.5/weather?q='+this.state.deesfault+"&units=imperial&appid=~~appid~~", function(data){
    selfish.setState(data);
    });
  },

  changeit: function() {
    this.setState({setting: false});
  },

  setsetting: function() {
    this.callthebase();
    this.setState({deesfault: document.getElementById('section').value});
    this.setState({setting: true});
  },

  changesection: function() {
    if (this.state.setting) {
      return (<p onClick={this.changeit}>In {this.state.deesfault}</p>)}

    else { return (<textarea id="section" defaultValue={this.state.deesfault} onBlur={this.setsetting} />) }
    },

  render: function() {
    return (
      <div>
        {this.changesection()}
        <p>The weather is {this.state.main.temp}</p>
      </div>
    )
  }
});

照原样,我必须输入一个位置,使其模糊,然后再次进入,激活它,然后再次使其模糊,以使代码实际执行我想要的操作。 当我使用纯虚拟文本时,这似乎不是问题。 但是,当我进行API调用时,就会出现此问题。

您正在调用callthebase,然后将deesfault设置为新值。

setsetting: function(){
  this.callthebase();
  this.setState({deesfault: document.getElementById('section').value});
  this.setState({setting: true});

},

在调用callthebase之前更改它不会解决您的问题,因为setState是异步调用的:

文档中:

setState()不会立即使this.state发生突变,但会创建一个挂起的状态转换。 调用此方法后访问this.state可能会返回现有值。

您可以做的是这样的:

setsetting: function(){
      var newValue = document.getElementById('section').value;
      this.callthebase(newValue);
      this.setState({deesfault: newValue, setting: true});
    },

当然可以修改callthebase以采用新值。

PS避免分配this一个变量,以便能够使用它的功能里面,你可以使用箭头功能从ES6代替:)

callthebase: function(newValue){
    $.get('http://api.openweathermap.org/data/2.5/weather?  q='+newValue+"&units=imperial&appid=~~appid~~", (data) => {
        this.setState(data);
    });
},

如何为您的文本区域添加onChange属性:

_onChange: function(event) {
   var value = event.target.value;

   // process value and update state here
},

<textarea id="section" defaultValue={this.state.deesfault} onChange={this._onChange} />

以下更改应该起作用

componentDidMount:function() {
let data = this.callthebase(this.state.deesfault);
this.setState(data)},

callthebase: function(newValue){
return $.get('http://api.openweathermap.org/data/2.5/weather?  q='+newValue+"&units=imperial&appid=~~appid~~", (data) => data);},

setsetting: function(){
  let oldValue = document.getElementById('section').value;
  let newValue = this.callthebase(oldValue);
  this.setState({deesfault: newValue, setting: true});
},

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM