如何在React.js中添加多个事件处理程序到同一个事件 [英] How to add multiple event handlers to same event in React.js

查看:271
本文介绍了如何在React.js中添加多个事件处理程序到同一个事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部:

我想知道是否有可能将多个事件处理程序绑定到同一个事件?

I wonder if it is possible that binding multiple event handlers to same event?

例如:

var LikeToggleButton = React.createClass({
    render: function(){
        (function toggle(){
            this.setState({liked:!like});
        }).bind(this);
        return (
            <div onClick={toggle}>TOGGLE LIKE</div>  
        );
    }
});

直到这一切,一切似乎都很正常,但是我想为该按钮添加另一个功能,这是决定通过其他选项:

Until this point everything seems normal, but I want to add another feature to that button, which is decide by other option:

例如,我有另一个开关组件(可以是像复选框或单选按钮等)称为计数切换,当启用时, LikeToggleButton的按钮将添加另一个onClick处理程序,它是开始计数按钮点击的次数,我知道它可能是preesignd进入切换功能,但我只是想知道是否有办法将这部分附加到onClick处理程序? strong>

For example, I have another switch component(could be anything like checkbox or radio button etc.) called "count toggle", which when enabled, the LikeToggleButton's button will be added another onClick handler which is start counting times of button clicked, I know it could be predesignd into the toggle function, but I just wonder if there is a way to append this part to onClick handler?

谢谢

推荐答案

如果你想拥有多个回调当onClick被触发时执行,您可以让它们从外部传递,因此您可以在道具对象中访问它们。然后执行它们(注意:代码未测试):

If you want to have multiple callbacks executed when onClick is triggered, you can have them passed from outside, so you'll have access to them in the props object. Then execute them all (note: code not tested):

var LikeToggleButton = React.createClass({

    toggle: function() {
        this.setState({liked:!like});
    },

    handleClick: function(e) {
        e.preventDefault();
        this.toggle();
        for (var i=0, l<this.props.callbacks.length; i<l; i++) {
           this.props.callbacks[i].call();
        }
    },

    render: function() {            
        return (
            <div onClick={this.handleClick}>TOGGLE LIKE</div>  
        );
    }
});

但是,如果要在其间连接组件,则不应该通过调用方法处理程序。相反,您应该使用架构模式,其中Flux是明显的选择(但还有更多)。

BUT, if you want to have components connected between them, you should not do that by calling methods inside handlers. Instead you should use an architectural pattern, where Flux is the obvious choice (but there are lots more).

查看 Flux ,此处您有更多选择

这篇关于如何在React.js中添加多个事件处理程序到同一个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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