反应点击处理程序并绑定它 [英] React click handlers and binding this

查看:45
本文介绍了反应点击处理程序并绑定它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个反应组件,我在其中迭代列表并创建行.每行都有一个删除按钮.单击删除按钮时,我想传递对该行中元素的引用.

I have a react component where I am iterating over a list and creating rows. In each row, there is a delete button. When the delete button is clicked, I want to pass a reference to the element in that row.

var TagTable = React.createClass({

        onTagDelete: function(tagName) {
            this.props.onTagDelete(tagName);
        },

        render: function () {
            return R.table({className: "bg-box padded"}, [
                R.thead({},
                    R.tr({}, [
                        R.th({}, ""),
                        R.th({}, "Tag"),
                        R.th({}, "Regexes")
                    ])),
                R.tbody({},
                    this.props.tags.map(function (tag) {
                        return R.tr({}, [
                            R.td({}, R.button({onClick: function() {this.onTagDelete(tag.name)}.bind(this), // BIND
                                className: "delete"}, "\u2716")),
                            R.td({key: "name"}, tag.name),
                            R.td({key: "regexes"}, tag.regexes.join(", "))]);
                    }.bind(this))) // BIND
            ])
        }
    }
);

所以为了在点击处理程序中保留 this-value;我对 map() 和点击处理程序都使用了绑定.

So in order to preserve the this-value in the click-handler; I use bind both for the map() and the click-handler.

这是在 React 中将参数传递给处理程序的正确方法还是有更好的方法?

Is this the proper way to pass arguments to handlers in React or is there a better way?

推荐答案

我对反应还很陌生,但我想我应该把它扔到这里来帮忙.

I'm fairly new to react, but I figured I'd throw this out here to help.

我认为你需要改变这一行,

I think you need to change this line,

R.td({}, R.button({onClick: function() {this.onTagDelete(tag.name)}.bind(this), // BIND
                            className: "delete"}, "\u2716")),

R.td({}, R.button({onClick: function() {this.onTagDelete.bind(this, tag.name)}, // BIND
                            className: "delete"}, "\u2716")),

我很确定现在应该将标签名称传递给函数.从单击的主题获取数据的另一种方法是通过 refs,但是对于项目列表,我认为由于重复的 ref 名称而效果不佳.所以我只会做你现在正在做的事情.

I'm pretty sure that this should now pass the tag name to the function. Another way of getting data from the clicked subject is through refs, but with lists of items I don't think this works well because of repeated ref names. So I would just do what you are doing now.

这篇关于反应点击处理程序并绑定它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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