In React, accessing onClick event value properties can be challenging, displaying console messages like "SyntheticMouseEvent {...}" instead of the desired value. This can be resolved by understanding React's event handling mechanism and employing appropriate techniques.
To pass a value to the onClick event using an arrow function, follow this approach:
return ( <th value={column} onClick={() => this.handleSort(column)}> {column} </th> );
This creates a new function that calls handleSort with the correct parameters.
For optimal performance, it's recommended to extract the onClick handling into a sub-component. This way, the handler reference won't change and unnecessary re-renders will be avoided.
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} /> ));}
The above is the detailed content of How Can I Pass a Value to an onClick Event in React?. For more information, please follow other related articles on the PHP Chinese website!