這篇文章將為大家詳細(xì)講解有關(guān)react如何創(chuàng)建組件,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
react創(chuàng)建組件的三種方式及他們的異同點(diǎn)介紹:
一、函數(shù)式組件
1、語法
function myConponent(props) { return `Hello${props.name}` }
2、特點(diǎn)
新增了hooks的API可以去官網(wǎng)了解下,以前是無狀態(tài)組件,現(xiàn)在是可以有狀態(tài)的了
組件不能訪問this對(duì)象
不能訪問生命周期方法
3、建議:
如果可能,盡量使用無狀態(tài)組件,保持簡(jiǎn)潔和無狀態(tài)?!竟P者的意思就是盡量用父組件去操控子組件,子組件用來展示,父組件負(fù)責(zé)邏輯】
二、es5方式React.createClass組件
1、語法
var myCreate = React.createClass({ defaultProps: { //code }, getInitialState: function() { return { //code }; }, render:function(){ return ( //code ); } })
2、特點(diǎn)
這種方式比較陳舊,慢慢會(huì)被淘汰
三、es6方式class:
1、語法:
class InputControlES6 extends React.Component { constructor(props) { super(props); this.state = { state_exam: props.exam } //ES6類中函數(shù)必須手動(dòng)綁定 this.handleChange = this.handleChange.bind(this); } handleChange() { this.setState({ state_exam: 'hello world' }); } render() { return( //code ) }; }
2、特點(diǎn):
成員函數(shù)不會(huì)自動(dòng)綁定this,需要開發(fā)者手動(dòng)綁定,否則this不能獲取當(dāng)前組件實(shí)例對(duì)象。
狀態(tài)state是在constructor中初始化
props屬性類型和組件默認(rèn)屬性作為組建類的屬性,不是組件實(shí)例的屬性,所以使用類的靜態(tài)性配置。
請(qǐng)大家瑾記創(chuàng)建組件的基本原則:
1、組件名首字母要大寫
2、組件只能包含一個(gè)根節(jié)點(diǎn)(如果這個(gè)根節(jié)點(diǎn)你不想要標(biāo)簽將它包住的話可以引入Fragment
3、盡量使用函數(shù)式組件,保持簡(jiǎn)潔和無狀態(tài)。
最后我們對(duì)比一下函數(shù)組件和class組件對(duì)于一個(gè)相同功能的寫法差距:
由父組件控制狀態(tài)的對(duì)比
函數(shù)組件:
function App(props) { function handleClick() { props.dispatch({ type: 'app/create' }); } return <div onClick={handleClick}>{props.name}</div> }
class組件
class App extends React.Component { handleClick() { this.props.dispatch({ type: 'app/create' }); } render() { return <div onClick={this.handleClick.bind(this)}>{this.props.name}</div> } }
自己維護(hù)狀態(tài)的對(duì)比
import React, { useState } from 'react'; function App(props) { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return <div onClick={handleClick}>{count}</div> }
class組件:
class App extends React.Component { state = { count: 0 } handleClick() { this.setState({ count: this.state.count +1 }) } render() { return <div onClick={this.handleClick.bind(this)}>{this.state.count}</div> } }
關(guān)于react如何創(chuàng)建組件就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
分享名稱:react如何創(chuàng)建組件-創(chuàng)新互聯(lián)
鏈接地址:http://chinadenli.net/article44/dhpgee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、動(dòng)態(tài)網(wǎng)站、云服務(wù)器、網(wǎng)站內(nèi)鏈、自適應(yīng)網(wǎng)站、網(wǎng)站收錄
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容
營(yíng)銷型網(wǎng)站建設(shè)知識(shí)