React - 具有参数的同一类中的事件 [英] React - Events in same class with parameters
问题描述
我正在使用Reactable来创建表格。单击操作框时,我想要一个框,通过更改样式显示有关该行的额外信息。
这是我到目前为止的代码:
I'm using Reactable to create a table. When clicked on the action box, I want a box with extra information about that row to appear by changing the style. This is my code so far:
var SelLines = new Object();
var Home = React.createClass({
handleClick: function(e) {
console.log("##Clicked##");
},
render: function() {
var tableRows = Data.map(function(tableRow) {
console.log(tableRow);
SelLines[tableRow.ID] = false;
console.log(SelLines);
if (SelLines[tableRow.ID]) {
return (
<Tr>
<Td column="ID">{tableRow.ID}</Td>
<Td column="DESCRIPTION">{tableRow.DESCRIPTION}</Td>
<Td className="cellSelected" column="ACTION"><a onClick={SelLines[tableRow.ID] = true;Home.handleClick}>{tableRow.ACTION}</a></Td>
//// = true;Home.h ## not working
</Tr>
);
} else {
return (
<Tr>
<Td column="ID">{tableRow.ID}</Td>
<Td column="DESCRIPTION">{tableRow.DESCRIPTION}</Td>
<Td className="cellNotSelected" column="ACTION"><a onClick={Home.handleClick}>{tableRow.ACTION}</a></Td>
</Tr>
);
}
});
return (
<div>
<div>
<Table className="table" id="table">
<Thead>
<Th column="ID">
<strong className="ID-header">ID</strong>
</Th>
<Th column="DESCRIPTION">
<em className="DESCRIPTION-header">DESCRIPTION</em>
</Th>
<Th column="ACTION">
<em className="ACTION-header">ACTION</em>
</Th>
</Thead>
{tableRows}
</Table>
</div>
</div>
);
}
});
如何将参数传递给handleClick?
How can I pass a parameter to handleClick?
推荐答案
您可以使用 function.bind()
在调用函数时添加要调用的参数。
You can use function.bind()
to prepend arguments to be called with when the function is invoked.
<a onClick={this.handleClick.bind(this, tableRow.ID)}>{tableRow.ACTION}</a>
handleClick: function(tableRowId, e) {
SelLines[tableRowId] = true;
console.log("##Clicked##", tableRowId);
}
因为你在 map()里面渲染
回调你还必须绑定回调:
Since you are rendering inside a map()
callback you also have to bind the callback:
var tableRows = Data.map(function(tableRow){
// ...
}.bind(this));
或者如果您使用ES6,您可以编写箭头功能避免需要 bind
:
var tableRows(Data.map((tableRow) => {
// ...
});
你可以编写一个内联箭头函数作为你的处理程序,它使用一些参数调用另一个函数:
And you can write an inline arrow function as your handler which calls through to another function with some arguments:
<a onClick={(e) => this.handleClick(tableRow.ID)}>{tableRow.ACTION}</a>
这篇关于React - 具有参数的同一类中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!