生活随笔
收集整理的這篇文章主要介紹了
React(二):类组件、函数式组件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Component(組件)可以是類組件(class component)、函數式組件(function component)。
1、類組件:
通常情況下,我們會使用ES6的class關鍵字來創建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區別
先了解下React生命周期函數shouldComponentUpdate,這個函數返回一個布爾值,如果返回true,那么當props或state改變的時候進行更新;如果返回false,當props或state改變的時候不更新,默認返回true。這里的更新不更新,其實說的是執不執行render函數,如果不執行render函數,那該組件和其子組件都不會重新渲染。
區別:
- 1、繼承PureComponent時,不能再重寫shouldComponentUpdate
- 2、React.PureComponent基于shouldComponentUpdate做了一些優化,通過prop和state的淺比較來實現shouldComponentUpdate,也就是說,如果是引用類型的數據,只會比較是不是同一個地址,而不會比較具體這個地址存的數據是否完全一致。
class ListOfWords extends React.PureComponent {
render() {
return <div>PureComponent渲染結果:{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() 方法返回一個新的數組對象
return (<div><button onClick={this.handleClick}>click</button><div>Component渲染結果:{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、函數式組件:
一個函數就是一個組件,
return一份DOM解構
特點:
1.沒有生命周期,也會被更新并掛載,但是沒有生命周期函數
2.沒有this(組件實例)
3.沒有內部狀態(state)
優點 :輕量,如果你的組件沒有涉及到內部狀態,只是用來渲染數據,那么就用函數式組件,性能較好。
復制代碼// 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、函數式組件與基于Class聲明的組件比較
不需要聲明類,可以避免大量的譬如extends或者constructor這樣的代碼
不需要顯示聲明this關鍵字,在ES6的類聲明中往往需要將函數的this關鍵字綁定到當前作用域,而因為函數式聲明的特性,我們不需要再強制綁定。
更佳的性能表現:因為函數式組件中并不需要進行生命周期的管理與狀態管理,因此React并不需要進行某些特定的檢查或者內存分配,從而保證了更好地性能表現。
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 上嘗試。
轉載于:https://juejin.im/post/5c0dfa265188257a5a2514d6
總結
以上是生活随笔為你收集整理的React(二):类组件、函数式组件的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。