一、什么是高階組件
高階組件( Higher-Order Component,HOC )是一個(gè)以組件作為參數(shù)
,返回一個(gè)新組件
的函數(shù)
。
- 高階組件最大的特點(diǎn)就是
復(fù)用組件邏輯
- 高階組件本身并不是 React 的 API,而是React組件的一種設(shè)計(jì)模式,一種組件重用的
高級(jí)技巧
- 高階組件是一個(gè)
函數(shù)
,接收要包裝的組件,返回增強(qiáng)后的組件
二、如何實(shí)現(xiàn)一個(gè)高階組件
高階組件內(nèi)部創(chuàng)建一個(gè)組件,在這個(gè)組件中提供復(fù)用的狀態(tài)邏輯
代碼,通過props
將復(fù)用狀態(tài)傳遞給被包裝組件 WrappedComponent
文章來源:http://www.zghlxwxcb.cn/news/detail-728297.html
- 創(chuàng)建一個(gè)函數(shù),命名
以 with 開頭
- 指定函數(shù)參數(shù),參數(shù)為組件,所以參數(shù)應(yīng)該以大寫字母開頭
- 在函數(shù)內(nèi)部創(chuàng)建一個(gè)組件,提供復(fù)用的狀態(tài)邏輯代碼,并返回
- 在該組件中,渲染參數(shù)組件,同時(shí)將狀態(tài)通過props傳遞給參數(shù)組件
- 調(diào)用該高階組件,傳入要增強(qiáng)的組件,通過返回值拿到增強(qiáng)后的組件,并將其渲染到頁(yè)面中
function withMouse(WrappedComponent) {
class Mouse extends React.Component {
state = {
x: 0,
y: 0,
}
render() {
return (
<WrappedComponent {...this.state}></WrappedComponent>
)
}
}
return Mouse
}
const Position = props => (
<div>
鼠標(biāo)位置: {props.x}, {props.y}
</div>
)
const MousePosition = withMouse(Position)
<MousePosition />
三、高階組件demo
- 代碼
import React from 'react'
/**
* 高階組件
*/
// 獲取組件名
// function getDisplayName(WrappedComponent) {
// return WrappedComponent.displayName || WrappedComponent.name || 'Component'
// }
// 創(chuàng)建高階組件
function withMouse(WrappedComponent) {
// 該組件提供復(fù)用的狀態(tài)邏輯
class Mouse extends React.Component {
// 初始化state
state = {
x: 0,
y: 0,
}
// 渲染UI,可以將state和props 一起傳遞給組件
render() {
return (
<WrappedComponent {...this.state} {...this.props}></WrappedComponent>
)
}
// 組件掛載,監(jiān)聽鼠標(biāo)移動(dòng)
componentDidMount() {
window.addEventListener('mousemove', this.handleMouseMove)
}
// 組件卸載,移除監(jiān)聽
componentWillUnmount() {
window.removeEventListener('mousemove', this.handleMouseMove)
}
// 鼠標(biāo)移動(dòng)事件處理程序
handleMouseMove = e => {
this.setState({
x: e.clientX,
y: e.clientY,
})
}
}
// 設(shè)置displayName 這個(gè)為了調(diào)試區(qū)分用,可以不設(shè)置
// Mouse.displayName = `WithMouse${getDisplayName(WrappedComponent)}`
// 返回增強(qiáng)后的組件
return Mouse
}
// 位置組件,用來測(cè)試高階組件
const Position = props => (
<div>
<h2>
鼠標(biāo)位置: {props.x}, {props.y}
</h2>
MousePosition組件: 接收的參數(shù) a == {props.a}
</div>
)
// 貓抓老鼠組件,用來測(cè)試高階組件
const Cat = props => (
<div>
<img
src={require('../../assets/images/cat.png')}
alt="貓"
height="22px"
style={{
position: 'absolute',
top: props.y - 10,
left: props.x - 10,
}}
/>
MouseCat組件: 接收的參數(shù) a == {props.a}
</div>
)
// 獲取增強(qiáng)后的組件
const MousePosition = withMouse(Position)
const MouseCat = withMouse(Cat)
// 使用
class MouseHigher extends React.Component {
// 渲染增強(qiáng)后的組件
render() {
return (
<div>
<MousePosition a="111"></MousePosition>
<MouseCat a="222"></MouseCat>
</div>
)
}
}
export default MouseHigher
- 效果
文章來源地址http://www.zghlxwxcb.cn/news/detail-728297.html
到了這里,關(guān)于react-高階組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!