简体   繁体   中英

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

I have a child component nested in a parent component. I want the parent component to get notified whenever an event takes place in a child component. In Vue, I could do this:

// 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" />

How can I achieve the same functionality in React?

Some clarification: I want an event to be emitted to the parent component whenever I like eg, when an item has been added to a list, and not just when a button is clicked.

One way you can achieve this is to give to the child component as props a function defined in the parent component.

In parent:

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

At the child definition:

<Child notify_parent ={notify_me} />

In Child component:

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

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