简体   繁体   中英

How to get button id using onclick Reactjs

i am working on Reactjs and using Nextjs, I am using "functional component" (not class),I have button inside loop and i want to get id of button using "onClick",But i am getting following error this is undefined Here is my current code

const deleteReview=async({currentTarget})=>
     {
        alert(currentTarget.value);
     }


{
    reviewfromserver.map(reviewnew=>{
        return(
                <div key={reviewnew.id}>
                    <div>{reviewnew.id}- {reviewnew.title} 
                        <button onClick={this.deleteReview} >Delete</button>
                    </div>
               </div>
              )
           })
}
  1. Add an id to the button. Because you may have identical ids somewhere else in your page I would recommend adding it as a data attribute . You can then pick up the id from the element's data set in the handler.

  2. You appear to be confusing calling class methods in a React class component with calling functions in a React function component. There's no need for this preceding the function name.

  3. There's no reason for that handler to be async .

 const { useState } = React; function Example({ reviewfromserver }) { function deleteReview(e) { console.log(e.target.dataset.id); } return ( <section> {reviewfromserver.map(reviewnew => { return ( <div key={reviewnew.id}> <div>{reviewnew.id} - {reviewnew.title} <button data-id={reviewnew.id} onClick={deleteReview} >Delete </button> </div> </div> ) })} </section> ); } const reviewfromserver = [ { id: 1, title: 'One' }, { id: 2, title: 'Two' }, { id: 3, title: 'Three' }, ]; ReactDOM.render( <Example reviewfromserver={reviewfromserver} />, document.getElementById('react') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

You have two options:

Option 1:

bind use it like this

 const deleteReview = async (id) => { alert(id); } { reviewfromserver.map(reviewnew=>{ return( <div key={reviewnew.id}> <div>{reviewnew.id}- {reviewnew.title} <button onClick={this.deleteReview.bind(this,reviewnew.id)} >Delete</button> </div> </div> ) }) }

option 2

Write two function:

 const deleteReview = async (id) => () => { alert(id); } { reviewfromserver.map(reviewnew=>{ return( <div key={reviewnew.id}> <div>{reviewnew.id}- {reviewnew.title} <button onClick={this.deleteReview(reviewnew.id)} >Delete</button> </div> </div> ) }) }

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