判断一个元素是否是由无状态的功能组件创建的

Telling if an element was created from a stateless functional component

本文关键字:状态 功能 创建 组件 是否是 元素 一个 判断      更新时间:2023-09-26

我是React Flip Move的所有者,这是一个小库,可以帮助在DOM节点重新排序时动画转换。

它通过使用refs工作;我克隆提供的children并附加一个ref函数,该函数将授予我对底层节点的访问权,并且我使用该引用根据需要进行命令式动画。

但是,无状态功能组件不支持ref。当传入一个SFC时,它抛出一个异常。

当前的错误消息非常没有帮助,我想提供一个更明确的警告。问题是,我不知道如何判断React元素是否从SFC创建。检查props.children,它们看起来几乎相同。

我当然可以通过在try/catch中包装第一个调用来找出它,但我希望比这更明确(而且,我不想等到第一次动画尝试才触发自定义错误消息)。

我不知道这是否有帮助,但是你怎么看这个:

class StatefulComponent extends React.Component {...}
console.log(typeof StatefulComponent.prototype.isReactComponent); // logs 'object'
const StatelessComponent = () => {...}
console.log(typeof StatelessComponent.prototype.isReactComponent); // logs 'undefined'

然而,我会尽快尝试React Flip Move。不错的工作!

编辑:

所以如果你想知道你的基组件的子组件是否是一个React组件:

// logs 'object' if it's a React Component otherwise logs 'undefined'
console.log(typeof this.props.children.type.prototype.isReactComponent);