三种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}
结果画面: