具有Reactjs的同一事件和元素的多个事件处理程序

编程入门 行业动态 更新时间:2024-10-23 14:25:40
本文介绍了具有Reactjs的同一事件和元素的多个事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写输入元素的扩展版本。以下是它的简化版本:

I'm writing an extended version of the input element. Here is a simplified version of it:

var MyInput = React.createClass({ render: function () { return ( <div> <input type="text" onChange={this.changeHandler} {...this.props} /> </div> ); }, changeHandler: function(event){ console.log('Trigger me first'); } });

我在这样的上下文中使用它:

I'm using it in a context like this:

<MyInput placeholder="Test" value={this.state.myValue} onChange={function(event){ console.log('Trigger me second'); }} />

因为你可能怀疑一个 onChange 覆盖另一个取决于属性的顺序。

As you are probably suspecting one onChange overrides the other depending on the order of the attributes.

考虑到这一点,您认为对于同一事件实现多个事件处理程序支持的最简洁方法是什么? ,对于像这样的情况下的相同元素?

With that in mind, what do you think would be the cleanest way to implement support for multiple event handlers for the same event, for the same element in cases like this one?

编辑


我能够交换 onChange 和 {... this.props} 并使用

changeHandler: function(event) { console.log('input_changeHandler change'); this.props.onChange(event); }

但我担心它是否安全。

But I'm concerned if it's safe.

推荐答案

来自这里的文档 facebook.github.io/react/docs/jsx-spread.html

规范顺序很重要。以后的属性会覆盖以前的属性。

因此,如果在传播之后放置onChange,它将始终优先。然后,您可以调用从您自己的处理程序传入的onChange函数。

So if you put your onChange after the spread, it will always take precedence. You can then call the onChange function passed in from your own handler.

var MyInput = React.createClass({ render: function () { return ( <div> <input type="text" {...this.props} onChange={this.changeHandler} /> </div> ); }, changeHandler: function(event){ console.log('Trigger me first'); if (typeof this.props.onChange === 'function') { this.props.onChange(event); } } });

更多推荐

具有Reactjs的同一事件和元素的多个事件处理程序

本文发布于:2023-10-27 00:07:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531742.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   多个   元素   程序   Reactjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!