React js onClick无法将值传递给方法 [英] React js onClick can't pass value to method
问题描述
我想阅读onClick事件值属性。但是当我点击它时,我在控制台上看到类似的东西:
I want to read the onClick event value properties. But when I click on it, I see something like this on the console:
SyntheticMouseEvent {dispatchConfig: Object, dispatchMarker: ".1.1.0.2.0.0:1", nativeEvent: MouseEvent, type: "click", target
My代码工作正常。当我运行时,我可以看到 {column}
,但无法在onClick事件中获取它。
My code is working correctly. When I run I can see {column}
but can't get it in the onClick event.
我的代码:
var HeaderRows = React.createClass({
handleSort: function(value) {
console.log(value);
},
render: function () {
var that = this;
return(
<tr>
{this.props.defaultColumns.map(function (column) {
return (
<th value={column} onClick={that.handleSort} >{column}</th>
);
})}
{this.props.externalColumns.map(function (column) {
// Multi dimension array - 0 is column name
var externalColumnName = column[0];
return ( <th>{externalColumnName}</th>
);
})}
</tr>);
}
});
如何将值传递给 onClick
React js中的事件?
How can I pass a value to the onClick
event in React js?
推荐答案
Easy Way
使用箭头功能:
Easy Way
Use an arrow function:
return (
<th value={column} onClick={() => this.handleSort(column)}>{column}</th>
);
这将创建一个调用 handleSort
使用正确的参数。
This will create a new function that calls handleSort
with the right params.
将其解压缩为子组件。
在渲染调用中使用箭头函数的问题是它每次都会创建一个新函数,最终导致不需要的重新渲染。
Extract it into a sub-component. The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.
如果你创建一个子函数组件,你可以传递处理程序并使用道具作为参数,然后只有当道具改变时才重新渲染(因为处理程序引用现在永远不会改变):
If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):
子组件
class TableHeader extends Component {
handleClick = () => {
this.props.onHeaderClick(this.props.value);
}
render() {
return (
<th onClick={this.handleClick}>
{this.props.column}
</th>
);
}
}
主要组件
{this.props.defaultColumns.map((column) => (
<TableHeader
value={column}
onHeaderClick={this.handleSort}
/>
))}
Old Easy Way(ES5)
使用 .bind
传递你想要的参数:
Use .bind
to pass the parameter you want:
return (
<th value={column} onClick={that.handleSort.bind(that, column)}>{column}</th>
);
这篇关于React js onClick无法将值传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!