javascript 将参数传递给 reactjs 单击处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29188326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass argument to reactjs click handler
提问by TGH
I have a question about passing arguments to React click handlers. I have the following code, but for some reason the node argument is not passed to the toggle function. Shouldn't it? It's defined this way because it's a recursive component.
我有一个关于将参数传递给 React 单击处理程序的问题。我有以下代码,但由于某种原因,节点参数没有传递给切换函数。不应该吗?它是这样定义的,因为它是一个递归组件。
var Element = React.createClass({
toggle: function(e,node){
},
render: function(){
var nodes = this.props.children.map(function(n){
return <Element node={n} text={n.text} children={n.children} />
});
return (
<span onClick={this.toggle.bind(this,this.props.node)}>{this.props.text}</span>
);
}
});
回答by Daniel Baulig
Function.prototype.bindbind arguments beginning from left. The correct way to receive the node argument is to look for it at the very left position of the argument list:
Function.prototype.bind从左边开始绑定参数。接收节点参数的正确方法是在参数列表的最左侧位置查找它:
toggle: function(node, event) {
console.log('node', node);
console.log('event', event);
}
See http://jsfiddle.net/8xxfgce7/for an example.
有关示例,请参见http://jsfiddle.net/8xxfgce7/。
回答by bir_ham
While the above answer is correct. Here is another example how to pass both eventand parameterto onClickfunction.
虽然上面的答案是正确的。这是另一个如何将事件和参数传递给onClick函数的示例。
Your event firing element e.g a button:
您的事件触发元素,例如按钮:
<button onClick={this.editTask.bind(this, item._id)}>
Edit item
</button>
Event handler function:
事件处理函数:
editItem(id, event) {
event.preventDefault() // Prevents default form submission
console.log('id: ', id) // Prints the item id
.
.
.
}

