Home >Web Front-end >JS Tutorial >How to Pass Values to onClick Events in React JS?
React's onClick event handler doesn't directly allow for value passing. When clicked, it displays a SyntheticMouseEvent object on the console. To pass values effectively, follow these solutions:
Use an arrow function:
return ( <th value={column} onClick={() => this.handleSort(column)}> {column} </th> );
This creates a function that invokes handleSort with the desired parameters.
Extract the code into a sub-component:
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} /> ))}
This ensures re-rendering only when necessary.
Bind the function to the Component context:
return ( <th value={column} onClick={this.handleSort.bind(this, column)}> {column} </th> );
The above is the detailed content of How to Pass Values to onClick Events in React JS?. For more information, please follow other related articles on the PHP Chinese website!