首先打個廣告,系列文章:react
下面進入正題:數組
咱們寫的純函數組件只負責處理展現,不少時候會發現,因爲業務需求,組件須要被「加強」,例如響應瀏覽器事件等。若是隻有一兩個組件咱們大能夠所有重寫爲class形式,但若是有許多組件須要進行類似或相同的處理(例如都響應瀏覽器窗口改變這個事件)時,考慮到代碼的複用性,很容易想到用函數處理,HOC也正是爲了解決這樣的問題而出現的。瀏覽器
說白了,高階組件的存在和React mixins相似,都是爲了解決代碼複用的問題。bash
HOC高階組件的基本原理能夠寫成這樣:dom
const HOCFactory = (Component) => {
return class HOC extends React.Component {
render(){
return <Component {...this.props} />
}
}
}
複製代碼
很明顯HOC最大的特色就是:接受一個組件做爲參數,返回一個新的組件。函數
咱們還沿用上篇文章中響應鼠標事件的的🌰。ui
import React from 'react'
import ReactDOM from 'react-dom'
const withMouse = (Component) => {
return class extends React.Component {
state = { x: 0, y: 0 }
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
})
}
render() {
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
<Component {...this.props} mouse={this.state}/>
</div>
)
}
}
}
// APP是一個純函數無狀態組件
const App = (props) => {
const { x, y } = props.mouse
return (
<div style={{ height: '100%' }}>
<h1>The mouse position is ({x}, {y})</h1>
</div>
)
}
const AppWithMouse = withMouse(App)
ReactDOM.render(<AppWithMouse/>, document.getElementById('root'))
複製代碼
因此即便React HOC(高階組件)比古老的React mixins在解決代碼複用問題上進步了很多,可是依然不能使人滿意。進一步的方案,參考下篇文章:React render props。this