简体   繁体   English

如何使用react触发变更事件

[英]How to trigger a change event using react

Currently I have this function in backbone. 目前,我在骨干网中具有此功能。

It update the model when onChange event is triggered. 触发onChange事件时,它将更新模型。

bindElementToAttribute: function(el, name, eventType) {
    var that = this;
    eventType = typeof(eventType) != 'undefined' ? eventType : "change";
    $(el).on(eventType, function() {
      var obj = {};
      obj[name] = $(el).val();
      that.model.set(obj, {silent: true});
      return true;
    });

I'm using a datepicker component of react to add a date field in this model, but this function of backbone does not trigger the onChange event when I select the date. 我正在使用react的datepicker组件在此模型中添加日期字段,但是当我选择日期时,骨干网的此功能不会触发onChange事件。 This is the component : https://github.com/Hacker0x01/react-datepicker 这是组件: https : //github.com/Hacker0x01/react-datepicker

In my component, I manually triggered the 'change' event 在我的组件中,我手动触发了“更改”事件

handleChange(date) {
    this.setState({
      startDate: date
    });
    $('input[name=release_date]').trigger('change')
  }

This is working fine, but when I select a new date in the datepicker, it pass the old value to the model. 这工作正常,但是当我在日期选择器中选择新日期时,它将旧值传递给模型。 When onchange is triggered the value has not yet updated. 触发onchange时,该值尚未更新。

How can I fix this? 我怎样才能解决这个问题?

Thanks everyone 感谢大家

This is probably because you trigger the event before your component re rendered as a result of setState , therefore you get the Dom's old value. 这可能是因为您在setState结果重新渲染组件之前触发了事件,因此获得了Dom的旧值。

Two options to solve this: 有两个解决方案:

1.You can pass setState a callback function as second parameter, like this: 1.您可以将setState作为第二个参数传递给回调函数,如下所示:

this.setState({
  startDate: date
}, function(){$('input[name=release_date]').trigger('change')});

the callback function will be executed once setState is completed and the component is re-rendered.(read more here: http://reactjs.cn/react/docs/component-api.html#setstate ). setState完成并重新呈现组件后,将执行回调函数。(更多信息请参见http://reactjs.cn/react/docs/component-api.html#setstate )。

2.And more React-ish- pass a callback function as prop to your component and execute it handleChange instead of triggering an input change. 2,更多的React-ish-将回调函数作为prop传递给组件,并执行handleChange而不是触发input更改。 like this: 像这样:

handleChange(date) {
  this.setState({
    startDate: date
  });

  this.prop.onChangeCallback(date);
}

* You can execute the onChangeCallback , at specific points in your component's lifecycle. *您可以在组件生命周期中的特定时间执行onChangeCallback read about Lifecycle Methods to decide on which point. 阅读有关生命周期方法以决定哪一点的信息。

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

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