简体   繁体   English

将 function 附加到 React 中的功能组件

[英]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

<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".例如,如果你使用 TypeScript,你会使这部分代码的输入更加困难,而且 React 实际上还使用了其他“保留”属性,例如“propTypes”或“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.现在您没有将属性附加到 React 内部使用的组件,但仍然具有您需要的分组和灵活性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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