三种React Componemt元件,功能类似,但有一些微妙的不同

三种React Componemt元件,通通都可以使用,但有一些微妙的不同

以下这三个元件的功能是相类似的。
以class 建立的元件
1.需要继承React.Component
2.需要实作方法render(){return ......}
3.具有state与生命周期
4.使用props需再多加this.

class Test extends React.Component {    render() {      return <h1>Hello , {this.props.name}</h1>;    }  }

以 JavaScript 函数定义元件
1.无生命周期。

  function Test01(props) {    return <h1>Hello , {props.name}</h1>;  }

Pure Componemt箭头函数
不需生命周期,不用state,不需处理资料或元件内部的状态,官方建议此种做法。

  const Test02 =(props)=>(      <h1>Hello , {props.name}</h1>      //不需要return   )    

完整代码

index.html

<!DOCTYPE html><html lang="en">  <head>  </head>  <body>    <div id="root"></div>  </body></html>

index.js

import React from 'react';import ReactDOM from 'react-dom';import {Test,Test01,Test02} from './test';//test.js中有多个元件,所以用大括号。ReactDOM.render(  <div>    <Test name='Test'/>    <Test01 name='Test01'/>    <Test02 name='Test02'/>  </div>  ,document.getElementById('root')   );

test.js

import React from "react";class Test extends React.Component {    render() {      return <h1>Hello , {this.props.name}</h1>;    }  }    function Test01(props) {    return <h1>Hello , {props.name}</h1>;  }    const Test02 =(props)=>(      <h1>Hello , {props.name}</h1>  )    export {Test,Test01,Test02};//一个js档输出多个元件就用export {a,b,c}

结果画面:
http://img2.58codes.com/2024/20122648YkPScEsteF.jpg


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章