简体   繁体   中英

React: cannot read property of undefined when passing in my onClick function

I am not sure why I am getting "TypeError: Cannot read property 'handleClickSimilar' of undefined" error when trying to use my function when mapping the array.

     handleClickSimilar = (d) => {
        console.log("testing click") 
    }


 render() {
      (...rest of my component)  
      <div className="bottom-content-right">
        <h3>Participating countries:</h3>
        {otherCountries && otherCountries.map(function(d, idx){
          return (<div onClick={() => this.handleClickSimilar(d)} key={idx}>{d}</div>)
        })}
      </div>

You need to make otherCountries.map function an arrow function (ie (d, idx) => ).

Replace otherCountries.map(function(d, idx){ with otherCountries.map((d, idx) =>{

So it will be like

{otherCountries && otherCountries.map((d, idx) => {
  return (<div onClick={() => this.handleClickSimilar(d)} key={idx}>{d}</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