Home > Web Front-end > JS Tutorial > How Can I Efficiently Pass Values to onClick Event Handlers in React JS?

How Can I Efficiently Pass Values to onClick Event Handlers in React JS?

Linda Hamilton
Release: 2024-11-28 03:25:11
Original
862 people have browsed it

How Can I Efficiently Pass Values to onClick Event Handlers in React JS?

React js onClick Event Value Passing

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>
);
Copy after login

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>
    );
  }
}
Copy after login

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}
  />
))}
Copy after login

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>
);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template