我想做React对onClickonChange等所做的事情.

React可以:

onClick={(event)=>console.log(event)}

我想做:

someProp={(wanna_do_this)=>console.log(wanna_do_this)}

推荐答案

您只需创建一个按您想要的命名的props 并传递它.例如:

import PropTypes from 'prop-types';
function CalledComponent ({onCustom}){
   // Here you'll be able to call this custom event/function.
   // Let's say I call it in useEffect.
   useEffect(onCustom, []);
   // Or maybe I call it in many events at the same time.
   return (<div onClick={(e)=>onCustom(e)} onHover={(e)=>onCustom(e)}>
         I'm called and I execute custom events when I'm clicked or hovered :D
   </div>);
}
// PropTypes stuff.
CalledComponent.propTypes = {
   onCustom: PropTypes.func,
};

所以稍后我可以简单地调用它并向它传递一个函数.

function ComponentThatCalls(){
    return (<CalledComponent onCustom={(e)=>console.log(e.target.value)}/>);
}

Javascript相关问答推荐

JavaScript替换子 node 导致它们更改为[对象HTMLTable SectionElement]

为什么它无法识别日期 Select 器上的任何 Select ?

我的JS代码将按照哪个序列被解释

使用Element.children在前后移动 node

v-textfield的规则找不到数据中声明的元素

为什么这个自定义组件会被放置在TR之外?

脚本.js:3:20未捕获的类型错误:无法读取空的属性(读取addEventHandler)

一次仅播放一个音频

React存档iframe点击行为

使用JavaScript在ionic Web应用程序中更新.pane和.view的背景 colored颜色

如何在angular中从JSON值添加动态路由保护?

处理时间和字符串时MySQL表中显示的日期无效

虚拟滚动实现使向下滚动可滚动到末尾

我的角模板订阅后不刷新'

我怎么才能得到Kotlin的密文?

如何发送从REST Api收到的PNG数据响应

当我在Reaction中创建一个输入列表时,我的输入行为异常

try 使用PM2在AWS ubuntu服务器上运行 node 进程时出错

为什么当我更新数据库时,我的所有组件都重新呈现?

如何在尚未创建的鼠标悬停事件上访问和着色div?