ReactJS在使用父值的子级中使用按钮调用父方法

时间:2020-05-13 01:28:03

标签: javascript reactjs react-native parent-child

我有以下问题:

我在上级组件中渲染了一个card元素。要渲染它,我使用以下代码:

父母:

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']}
   />
  )}
)}

儿童: 在这里,我有一张带有“喜欢”按钮的卡片。

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;

我正在尝试打印由父方的地图功能生成的每个“喜欢”按钮的唯一ID。但是我不能把头缠住它。它给我:每次都无法读取未定义的属性“ props”。

能帮我一下吗? 先感谢您。

1 个答案:

答案 0 :(得分:0)

“无法读取未定义的道具” 的原因是该函数进入子组件并被事件处理程序调用时,该函数未在 Home / Child / WordCard或定义该功能的任何组件的上下文

在将其传递给事件之前,请尝试将该函数绑定到要调用的上下文上。

有关家用组件中的解决方案

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);
}

使用任何一种方式,但不能同时使用。