簡體   English   中英

我如何在 React 中將事件從子組件發送到父組件?

[英]How do I emit events from a child component to a parent component in React?

我有一個嵌套在父組件中的子組件。 我希望父組件在子組件中發生事件時得到通知。 在 Vue 中,我可以這樣做:

// inside the child component EventButton

// the event 'someEvent' gets emitted whenever the button is clicked
<button @click="$emit('someEvent')">
  Emit event
</button>
// inside the parent component

<EventButton @someEvent="() => do something" />

我怎樣才能在 React 中實現相同的功能?

一些說明:我希望每當我喜歡時將事件發送到父組件,例如,當一個項目被添加到列表中時,而不僅僅是單擊按鈕時。

實現此目的的一種方法是將父組件中定義的函數作為 props 提供給子組件。

在父母:

function notify_me(){
     #do what you want to do in the parent component using a state for example
}

在子定義中:

<Child notify_parent ={notify_me} />

在子組件中:

<EventButton @someEvent={() => props.notify_me()}/>

暫無
暫無

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

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