首页 > 解决方案 > React 功能组件 - 测试一个元素 instanceOf baseElement

问题描述

在旧的方式反应组件(基于类的组件)中,
很容易确定指定的子/元素是 baseComponent 的类型。
像这样的东西:

class CatComponent extends React.Component { /* ... */ }

class LionComponent extends CatComponent { /* ... */ }

/* ... */
<FooComponent>
{(Array.isArray(props.children) ? props.children : [props.children]).map((child, index) => {
   if (React.isValidElement(child) && (child.type.prototype instanceof CatComponent || child.type===CatComponent)) {
      return doSomething(child);
   }
   else {
      return doAnother(child);
   }
})}
</FooComponent>
/* ... */

问题是,像这样的功能组件怎么样:

function CatComponent() { /* ... */ }

function LionComponent() { return <CatComponent>
   <AnotherComp>
   </AnotherComp>
</CatComponent> }

有没有办法确定LionComponent是那种CatComponent

child.type指向但LionComponent我不知道确定LionComponent是那种CatComponent

标签: reactjsreact-functional-component

解决方案


推荐阅读