如何像 React 在 onChange、onClick 等中公开“param”?

问题描述 投票:0回答:1

我想做 React 用

onClick
onChange
等做的事情

React 会:

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

我想做:

someProp={(wanna_do_this)=>console.log(wanna_do_this)}
javascript reactjs
1个回答
0
投票

你只需创建一个你想要命名的 prop 并传递它。例如:

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={onCustom} onHover={onCustom}>
         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(){
    const onCustomEvent = (e) => console.log(e.target.value);
    return (<CalledComponent onCustom={onCustomEvent}/>);
}
© www.soinside.com 2019 - 2024. All rights reserved.