Passing Values to onClick Events in React
React's onClick event handler does not natively accept parameters. When onClick is triggered, it displays synthetic event properties devoid of any explicit value transfer. To overcome this, several approaches can be employed:
Arrow Function (Easy Way)
An arrow function can be used to manually pass values to the onClick handler:
return ( <th value={column} onClick={() => this.handleSort(column)}>{column}</th> );
This creates a new function that invokes handleSort with the desired parameters. However, excessive function creation can lead to unnecessary re-renders.
Sub-Component (Optimal Method)
Extracting the handler into a sub-component enhances performance by preventing excessive re-rendering:
Sub-component
class TableHeader extends Component { handleClick = () => { this.props.onHeaderClick(this.props.value); } render() { return ( <th onClick={this.handleClick}> {this.props.column} </th> ); } }
Main Component
{this.props.defaultColumns.map((column) => ( <TableHeader value={column} onHeaderClick={this.handleSort} /> ))}
ES5 Legacy Approach (Easy Way)
For ES5 compatibility, the following approach can pass values using .bind:
return ( <th value={column} onClick={this.handleSort.bind(this, column)}>{column}</th> );
By choosing the most appropriate technique, you can effectively pass values to onClick events in React and avoid the issue outlined in the question.
The above is the detailed content of How to Pass Values to onClick Events in React?. For more information, please follow other related articles on the PHP Chinese website!