簡體   English   中英

ReactJS 在使用父值的子按鈕中調用父方法

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

我有以下問題:

我有一個卡片元素,我在我的父組件中呈現。 要渲染它,我使用以下代碼:

家長:

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;

我正在嘗試打印在父端使用 map function 生成的每個“喜歡”按鈕的唯一 ID。 但我無法繞過它。 它給了我:每次都無法讀取未定義的屬性“道具”。

你能幫幫我嗎? 先感謝您。

“無法讀取未定義的道具”的原因是 function 在進入子組件並被事件處理程序調用時,然后 function不會在 Home/Child/WordCard 或其中的任何組件的上下文中調用function 被定義

在將它傳遞給事件之前,嘗試將 function 綁定到您希望調用它的上下文

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

使用任何一種方式,但不能同時使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM