繁体   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