简体   繁体   中英

Attach a function to a functional component in React

Have a child component which is

const Block = () => {}

Block.onClick = (props) => {
  return true/false
} 

Block.onSpan = () => {
  return true/false
}

We have a parent, let's call it DaddyBlock

<DaddyBlock customBlock={Block || undefined} />


const DaddyBlock = ({customBlock}) => {
   if(customBlock){
     handleClick = () => {/where we use result from customBlock.canClick/}
     handleSpan = () => {/where we use result from customBlock.canSpan/}
     const CustomBlock = customBlock;
     return <CustomBlock handleClick={handleClick} handleSpan={handleSpan} {...props} />
   }
   return <DefaultBlock />
}

I don't think that there is actually a real relevance to do it like that. If you would use TypeScript for instance, you would make typing of this part of the code harder and there are actually other "reserved" properties that are used by React, eg "propTypes" or "displayName". That is the reason why you shouldn't do it, as you did it.

Another approach just for grouping these kind of elements that is more clean is the following:

Block.Component = () => {}

Block.onClick = (props) => {
  return true/false
} 

Block.onSpan = () => {
  return true/false
}

Now you are not attaching the properties to the component that is used by React internally, but still have the grouping and flexibility you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM