When working with React js events, it may be challenging to pass values to methods. We'll address this issue by exploring multiple solutions.
1. Using Arrow Functions
The simplest method is to utilize an arrow function:
return ( <th value={column} onClick={() => this.handleSort(column)}>{column}</th> );
Arrow functions create new functions that call handleSort with the appropriate parameters. However, this approach generates a new function each time, leading to unnecessary re-renders.
2. Extracting to Sub-Components (Recommended)
A better approach is to extract onClick event handling into a sub-component. Create a sub-component that takes the handler and value as props:
class TableHeader extends Component { handleClick = () => { this.props.onHeaderClick(this.props.value); }; render() { return ( <th> <th onClick={this.handleClick}>{this.props.column}</th> </th> ); } }
In the main component, pass the handler and value props to the sub-component:
{this.props.defaultColumns.map((column) => ( <TableHeader value={column} onHeaderClick={this.handleSort} /> ))}
This ensures that the handler reference never changes, minimizing unnecessary re-renders.
3. ES5 Method (Old)
If you're using ES5, you can bind the function with the component context like so:
return ( <th value={column} onClick={this.handleSort.bind(this, column)}>{column}</th> );
The above is the detailed content of How Can I Efficiently Pass Values to onClick Event Handlers in React JS?. For more information, please follow other related articles on the PHP Chinese website!