当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


ReactJS isElement()用法及代码示例


React.js 库就是将应用程序拆分为多个组件。每个组件都有自己的生命周期。 React 为我们提供了一些内置方法,我们可以在组件的 life-cycle 中的特定阶段覆盖这些方法。

在本文中,我们将知道如何使用 isElement() 方法。如果元素是任何反应元素,则 isElement() 方法返回 true。

创建 React 应用程序并安装模块:

  • 步骤 1:使用以下命令创建 React 应用程序。

    npx create-react-app foldername



  • 第 2 步:创建项目文件夹(即文件夹名称)后,使用以下命令移至该文件夹。

    cd foldername

项目结构:如下图所示。

范例1:现在在 App.js 文件中写下以下代码。在这里,App 是我们编写代码的默认组件。

App.js


import React from 'react';
import { isElement } from 'react-dom/test-utils';
  
// Defining our App Component
const App = () => {
  
// Function to demonstrate isElement() method
function func() {
   var a = isElement(el);
   console.log("The Following is an element:", a);
}
  
const el = <div>
    <h1>element</h1>
</div>
  
// Returning our JSX code
return <>
    <div>
        <h1>GeeksforGeeks</h1>
        <button onClick={func}>Click Here !!</button>
    </div>;
</>;
}
  
// Exporting your Default App Component
export default App

运行应用程序的步骤:从项目的根目录中使用以下命令运行应用程序:

npm start

输出:现在打开浏览器并转到http://localhost:3000 /,您将看到以下输出:

范例2:现在在 App.js 文件中写下以下代码。在这里,App 是我们编写代码的默认组件。

App.js


import React from 'react';
import { isElement } from 'react-dom/test-utils';
  
// Defining our App Component
const App = () => {
  
// Function to demonstrate isElement() method
function func(){
   var element = document.getElementById('id')
   var a = isElement(element);
   console.log("The Following is an element:", a);
}
// Returning our JSX code
return <>
    <div id='el'>
        <h1>GeeksforGeeks</h1>
        <button onClick={func}>Click Here !!</button>
    </div>
</>;
}
  
// Exporting your Default App Component
export default App

运行应用程序的步骤:从项目的根目录中使用以下命令运行应用程序:

npm start

输出:现在打开浏览器并转到http://localhost:3000 /,您将看到以下输出:

参考:https://reactjs.org/docs/test-utils.html#iselement

相关用法


注:本文由纯净天空筛选整理自dheerchanana08大神的英文原创作品 ReactJS isElement() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。