首页 > 解决方案 > 在 React 中发出自定义事件

问题描述

在 Vue.js 中,我们可以发出自定义事件以及类似的参数

this.$emit('bark', 3);

然后我们可以在父组件上监听这个事件,比如

<parent-component @bark=handleBark />

handleBark (howManyTimes) {
    console.log(howManyTimes);
    // logs 3
}

我们如何在 React 中做到这一点?

标签: javascriptreactjs

解决方案


您只需将自定义事件处理程序作为props.

例如,如果您有Parent功能Child组件。然后,您可以在组件中定义自定义事件处理程序,Parent例如:

function Parent(props) {
  const handleBark = (howManyTimes) => {
    console.log(howManyTimes);
  };
  
  // note below I am sending the handleBark method to Child as props
  return (<Child bark={handleBark} />);
}

然后在Child组件内部,您可以简单地将其称为:

props.bark(10);

推荐阅读