How to detect a React component vs. a React element?

前端 未结 7 1940
广开言路
广开言路 2020-12-02 10:04

React.isValidElement tests true for both React components as well as React elements. How would I test, specifically, that an object is a React component? Curren

相关标签:
7条回答
  • 2020-12-02 10:31

    If you want to know what class you have for a particular instance of an object variable, then what you want is the instanceof operator...

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

    I tested with both document.createElement('div') (returns true) and <someReactJSComponent /> (returns false).

    instanceof is a powerful and useful tool in JavaScript. Check out the official MDN documentation for it: Mozilla Documentation Network: instanceof

    "The instanceof operator tests the presence of constructor.prototype in object's prototype chain."

    In addition, I have uploaded a code sample with a code-sandbox online to demonstrate the above principle...

    Online Code Sandbox :

    https://codesandbox.io/s/kmxjq27ol5

    Code :

    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) +
        "|"
    );
    

    Code Results :

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

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

    0 讨论(0)
提交回复
热议问题