javascript - 在 React 中发出自定义事件
问题描述
在 Vue.js 中,我们可以发出自定义事件以及类似的参数
this.$emit('bark', 3);
然后我们可以在父组件上监听这个事件,比如
<parent-component @bark=handleBark />
handleBark (howManyTimes) {
console.log(howManyTimes);
// logs 3
}
我们如何在 React 中做到这一点?
解决方案
您只需将自定义事件处理程序作为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);
推荐阅读
- java - scala中的Java类类型不匹配?
- ssl - 为什么在 .Net Core MVC 中出现 SSL 错误?
- c# - 我有一个关于当我将基于泛型的类作为单例添加到组件中时发生的错误的问题
- c++ - 使用 RE2::GlobalReplace 转义字符串
- c++ - 即使我没有#define 任何内容或错过分号,如何修复“字符串常量之前的预期不合格 ID”?
- arrays - 错误类型错误:无法读取未定义的属性“属性”
- c++ - Maya API - 从材质中获取网格
- javascript - 成功更改密码后 Firebase 重定向到网页
- html - 调整窗口大小时如何阻止按钮重叠
- javascript - 查找总和等于数字的所有子数组?