生活随笔
收集整理的這篇文章主要介紹了
React(二):类组件、函数式组件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Component(組件)可以是類組件(class component)、函數(shù)式組件(function component)。
1、類組件:
通常情況下,我們會使用ES6的class關(guān)鍵字來創(chuàng)建React組件。
a、類組件分為普通類組件(React.Component)以及純類組件(React.PureComponent)。
// Component
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;}
}
復制代碼// PureComponent
class Welcome extends React.PureComponent {
render() {
return <h1>Hello, {this.props.name}</h1>;}
}
復制代碼b、React.Component和React.PureComponent區(qū)別
先了解下React生命周期函數(shù)shouldComponentUpdate,這個函數(shù)返回一個布爾值,如果返回true,那么當props或state改變的時候進行更新;如果返回false,當props或state改變的時候不更新,默認返回true。這里的更新不更新,其實說的是執(zhí)不執(zhí)行render函數(shù),如果不執(zhí)行render函數(shù),那該組件和其子組件都不會重新渲染。
區(qū)別:
- 1、繼承PureComponent時,不能再重寫shouldComponentUpdate
- 2、React.PureComponent基于shouldComponentUpdate做了一些優(yōu)化,通過prop和state的淺比較來實現(xiàn)shouldComponentUpdate,也就是說,如果是引用類型的數(shù)據(jù),只會比較是不是同一個地址,而不會比較具體這個地址存的數(shù)據(jù)是否完全一致。
class ListOfWords extends React.PureComponent {
render() {
return <div>PureComponent渲染結(jié)果:{this.props.words.join(
',')}</div>;}
}
class WordAdder extends React.Component {constructor(props) {super(props);this.state = {words: [
'marklar']};this.handleClick = this.handleClick.bind(this);}
handleClick() {// This section is bad style and causes a bugconst words = this.state.words;words.push(
'marklar');this.setState({words: words});}
render() {// slice() 方法返回一個新的數(shù)組對象
return (<div><button onClick={this.handleClick}>click</button><div>Component渲染結(jié)果:{this.state.words.join(
',')}</div><ListOfWords words={this.state.words} /><ListOfWords words={this.state.words.slice(0)} /></div>);}
}
ReactDOM.render(<WordAdder />,document.getElementById(
'root')
);
復制代碼在 CodePen 上嘗試。
2、函數(shù)式組件:
一個函數(shù)就是一個組件,
return一份DOM解構(gòu)
特點:
1.沒有生命周期,也會被更新并掛載,但是沒有生命周期函數(shù)
2.沒有this(組件實例)
3.沒有內(nèi)部狀態(tài)(state)
優(yōu)點 :輕量,如果你的組件沒有涉及到內(nèi)部狀態(tài),只是用來渲染數(shù)據(jù),那么就用函數(shù)式組件,性能較好。
復制代碼// functional component
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
復制代碼//組合組件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (<div><Welcome name=
"Sara" /><Welcome name=
"Cahal" /><Welcome name=
"Edite" /></div>);
}ReactDOM.render(<App />,document.getElementById(
'root')
);
復制代碼3、函數(shù)式組件與基于Class聲明的組件比較
不需要聲明類,可以避免大量的譬如extends或者constructor這樣的代碼
不需要顯示聲明this關(guān)鍵字,在ES6的類聲明中往往需要將函數(shù)的this關(guān)鍵字綁定到當前作用域,而因為函數(shù)式聲明的特性,我們不需要再強制綁定。
更佳的性能表現(xiàn):因為函數(shù)式組件中并不需要進行生命周期的管理與狀態(tài)管理,因此React并不需要進行某些特定的檢查或者內(nèi)存分配,從而保證了更好地性能表現(xiàn)。
const Text = (props) =><p>{props.children}</p>;class App extends React.Component {
render() {
return <Text>Hello World</Text>;}
}
ReactDOM.render(<App />,document.getElementById(
'root')
);
復制代碼在 CodePen 上嘗試。
轉(zhuǎn)載于:https://juejin.im/post/5c0dfa265188257a5a2514d6
總結(jié)
以上是生活随笔為你收集整理的React(二):类组件、函数式组件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。