简体   繁体   中英

ReactJS Call parent method with a button in child that uses parent values

I have a following problem:

I got a card element that i render in my parent component. To render it i use the following code:

PARENT:

import WordCard from "./subComponents/card"

class Home extends Component {

state = {

words:['id1','id2','id3','id4']

}

parentMethod(data){
//my actual code here
//Right now just trying to at least print the 'uid' so:
     console.log(data)
}
...
render(){
...
return(...
  {this.state.words.map(i =>
   <WordCard 
     parentMethod={this.parentMethod} 
     uid = {i['_id']}
   />
  )}
)}

CHILD: Here i have a card with a 'like' button.

import React from 'react';
import { Button, Card } from 'react-bootstrap'

...

const cards = (props) => {

return (
...

<Card>
<Button onClick={() => this.props.parentMethod(this.props.uid)}  >

/Card>


...
}

export default cards;

I am trying to print a unique id of every 'like' button that is generated with map function on the parent side. But i can not wrap my head around it. It gives me: Cannot read property 'props' of undefined every time.

Could you please help me out. Thank you in advance.

The reason for "Can't read Props of Undefined" is that the function when goes inside the child component and being called by the event handler then the function is not called in the context of Home/Child/WordCard or any component in which the function is defined .

Before passing it to the event try binding the function to the context you want it to be called .

For a solution in Home Component

Class Home{
 constructor(){
   //Way 1
   this.methodName = this.methodName.bind(this);
 }
 ....
 methodName(){
   //Using this inside
   console.log(this.someThing); //Eg. this.state, this.props
 }

 //Way 2
 methodName = methodName.bind(this);
}

Use any of the Way but not both together.

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