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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33199959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:46:29  来源:igfitidea点击:

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

javascriptreactjs

提问by jedmao

React.isValidElementtests true for both React components as well as React elements. How would I test, specifically, that an object is a React component? Currently, I'm doing it by testing typeof obj.type === 'function', but I'm hoping there's a better way.

React.isValidElement对 React 组件和 React 元素都进行了测试。我将如何测试,具体来说,一个对象是一个 React 组件?目前,我正在通过测试来做到这一点typeof obj.type === 'function',但我希望有更好的方法。

采纳答案by Anvesh Checka

ReactComponent.prototype.isReactComponent = {};

33 of /node_modules/react/lib/ReactComponent.js

33 /node_modules/react/lib/ReactComponent.js

Install using npm. At this point, there is no direct method available to check for its validity. What you are doing is correct.

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

回答by Emanual Jade

If you really want to type check for

如果你真的想输入检查

  • component vs element

  • class vs functional component

  • DOM vs Composite Element

  • 组件与元素

  • 类与功能组件

  • DOM 与复合元素

You could try something like this.

你可以尝试这样的事情。

function isClassComponent(component) {
    return (
        typeof component === 'function' && 
        !!component.prototype.isReactComponent
    )
}

function isFunctionComponent(component) {
    return (
        typeof component === 'function' && 
        String(component).includes('return React.createElement')
    )
}

function isReactComponent(component) {
    return (
        isClassComponent(component) || 
        isFunctionComponent(component)
    )
}

function isElement(element) {
    return React.isValidElement(element);
}

function isDOMTypeElement(element) {
    return isElement(element) && typeof element.type === 'string';
}

function isCompositeTypeElement(element) {
    return isElement(element) && typeof element.type === 'function';
}

USE

// CLASS BASED COMPONENT
class Foo extends React.Component {
  render(){
      return <h1>Hello</h1>;
  }
}

const foo = <Foo />;

//FUNCTIONAL COMPONENT
function Bar (props) { return <h1>World</h1> }
const bar = <Bar />;

// REACT ELEMENT
const header = <h1>Title</h1>;

// CHECK
isReactComponent(Foo); // true
isClassComponent(Foo); // true
isFunctionComponent(Foo); // false
isElement(Foo); // false

isReactComponent(<Foo />) // false
isElement(<Foo />) // true
isDOMTypeElement(<Foo />) // false
isCompositeTypeElement(<Foo />) // true

isReactComponent(Bar); // true
isClassComponent(Bar); // false
isFunctionComponent(Bar); // true
isElement(Bar); // false

isReactComponent(<Bar />) // false
isElement(<Bar />) // true
isDOMTypeElement(<Bar />) // false
isCompositeTypeElement(<Bar />) // true

isReactComponent(header); // false
isElement(header); // true
isDOMTypeElement(header) // true
isCompositeTypeElement(header) // false

Example Codepen

示例代码笔

回答by Hymankobec

The simplest solution is:

最简单的解决方案是:

React.isValidElement(element)

回答by Christopher Regner

In addition to @EmanualJade answer, you can use this to check if a variable is a function component

除了@EmanualJade 答案之外,您还可以使用它来检查变量是否为 function component

React.isValidElement(Component())

As @Leonardo has pointed out, some compilers can cause this to fail:

正如@Leonardo 指出的那样,某些编译器可能会导致此失败:

String(component).includes('return React.createElement')

回答by Razzwan

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>

回答by HoldOffHunger

If you want to know what classyou have for a particular instanceof an object variable, then what you want is the instanceofoperator...

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

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

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

我测试了document.createElement('div')(返回真)和<someReactJSComponent />(返回假)。

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

instanceof是一个强大而有用的 JavaScript 工具。查看它的官方 MDN 文档:Mozilla 文档网络:instanceof

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

“instanceof 运算符测试对象原型链中constructor.prototype 的存在。”

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

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.

没问题(已测试 Chrome 和 FF)。只需使用instanceof.