具有Reactjs的同一事件和元素的多个事件处理程序 [英] Multiple event handlers for the same event and element with Reactjs

查看:84
本文介绍了具有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.

推荐答案

来自这里的文档 https://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的同一事件和元素的多个事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆