如何检测React组件与React元素?

JavaScript React.js

斯丁泡芙

2020-03-19

React.isValidElement对React组件和React元素均测试为true。我将如何具体测试对象是React组件?目前,我正在通过测试进行操作typeof obj.type === 'function',但我希望有更好的方法。

第2394篇《如何检测React组件与React元素?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
凯小卤蛋 2020.03.19

class Test extends React.Component {}

console.log(!!Test.prototype.isReactComponent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

蛋蛋前端 2020.03.19

如果你想知道什么你有一个特定实例对象变量,那么你想要什么的instanceof运算符...

function isHTMLElement(obj) {
    return (obj instanceof HTMLElement);
}

我同时测试了document.createElement('div')(返回true)和<someReactJSComponent />(返回false)。

instanceof是JavaScript中功能强大且有用的工具。查看官方MDN文档:Mozilla文档网络:instanceof

“ instanceof运算符测试对象的原型链中是否有builder.prototype。”

另外,我还在线上传了带有代码沙箱的代码示例,以演示上述原理...

在线代码沙箱:

https://codesandbox.io/s/kmxjq27ol5

代码:

function App() { return (//insert JSX here//);};
const app = App();
const ele = document.createElement("div");
const rootElement = document.getElementById("root");
ReactDOM.render(app, rootElement);
console.log(
  "Hello!  Is a React Component HTML???" +
    (app instanceof HTMLElement) +
    "|  Is an HTML element HTML???" +
    (ele instanceof HTMLElement) +
    "|"
);

代码结果:

Hello!  Is a React Element HTML???false|  Is an HTML element HTML???true|

No problem (tested Chrome and FF). Just use instanceof.

卡卡西逆天 2020.03.19

最简单的解决方案是:

React.isValidElement(element)
Davaid飞羽 2020.03.19
ReactComponent.prototype.isReactComponent = {};

/node_modules/react/lib/ReactComponent.js中的33

使用npm安装。在这一点上,没有直接的方法可用来检查其有效性。你在做什么是正确的。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android