[英]ReactJS onClick event inside map function, then call parent's function
I have just started to work with ReactJS and I can't figure out how I can make onClick events work inside a map function, which renders a few similar elements. 我刚刚开始使用ReactJS,但我不知道如何使onClick事件在map函数内部工作,该函数呈现了一些相似的元素。 When I am not using onClick={this.someMethodName} in the child elements, everything is working fine, so I am guessing the 'this' keyword no longer refers to the parent. 当我在子元素中不使用onClick = {this.someMethodName}时,一切工作正常,所以我猜'this'关键字不再指向父级。
Here is my code, which renders a simple menubar: 这是我的代码,它呈现了一个简单的菜单栏:
var SupplierBarComponent = React.createClass({
doSomething: function () {
console.log("aaaaaaaah");
},
render: function() {
const suppliers = this.props.data.map(function(supplier){
return (
<option onClick={this.doSomething} key={supplier.id}>{supplier.name}</option>
);
}, this);
return(
<div>{suppliers}</div>
);
}
How can I make it work? 我该如何运作? I have read a few similar questions*, but their solutions didn't work for me, or I couldn't make them work. 我读过一些类似的问题*,但是它们的解决方案对我而言不起作用,或者我无法使它们起作用。
*: React onClick inside .map then change data in another sibling component "this" is undefined inside map function Reactjs Pass props to parent component in React.js *: React onClick在.map内部,然后更改另一个兄弟组件 “ this”中的 数据, 这在映射函数Reactjs中未定义。将props 传递给React.js中的父组件
Your code is working. 您的代码正在运行。 I have checked it on this Fiddle.I just hardcoded an array instead of the props. 我已经在这个Fiddle上检查了它,我只是硬编码了一个数组而不是props。
var Hello = React.createClass({
doSomething: function () {
console.log("aaaaaaaah");
},
render: function() {
var data=[{id:1,name:'name 1'},{id:2,name:'name 2'}]
const suppliers = data.map(function(supplier){
return (
<option onClick={this.doSomething} key={supplier.id}>{supplier.name}</option>
);
}, this);
return(
<div>{suppliers}</div>
);
}
})
ReactDOM.render(
<Hello />,
document.getElementById('container')
);
https://jsfiddle.net/evweLre5/ https://jsfiddle.net/evweLre5/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.