简体   繁体   中英

How do I prevent ReactJS onclick function from running on render

I don't want the function to be called when the page loads but only when the user actually clicks the row

Here are my basic snippets:

JS

function readDetails(id){
    console.log(id)
}

JSX

<tr key={data.id} onClick={() => { readDetails (data.id)} }>

Method 1:

<tr key={data.id} onClick={() => readDetails(data.id)}>

Method 2:

const readDetails = (id) => {
  return () => {
    console.log(id)
  }
}

<tr key={data.id} onClick={readDetails(data.id)}>

You can solve this by changing

<tr key={data.id} onClick={readDetails (data.id)}>

To this:

<tr key={data.id} onClick={() => { readDetails(data.id) }}>

You should also be able to remove the extra curly braces like this:

<tr key={data.id} onClick={() => readDetails(data.id)}>

This will be supported on React 0.13.3 or above.

After many trials I realized calling a function within a table element doesn't really work well in ReactJS . The best option to solve this issue was to use divs and style them to suit my tabular pattern .

Then I passed the function this way

<div key={data.id} onClick={() => readDetails(data.id)}>
    Table Data
</div>

You can solve this by changing

<tr key={data.id}  onClick={function (e) {
e.preventDefault();
this.readDetails(data.id);
.bind(this)}></tr>

Considering you have a key prop in your example, I'm assuming you're looping over an array (or something similar) and outputting a collection of <tr> elements. Because of this, I'd recommend defining a function that you can just reference rather than defining a new function each loop for efficiency:

const readDetails = (e) => console.log(e.target.getAttribute('data-id'));
<tr key={data.id} data-id={data.id} onClick={readDetails}>

You have to define an extra prop however (in this case data-id) because the key prop is not available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM