高階函數
- 高階函數是指滿足下列條件之一的函數
1、接受一個或多個函數作為輸入;
2、返回一個函數;
Mixins的缺點
1、破壞組件封裝性:Mixin可能會引入不可見的屬性。例如在渲染組件中使用Mixin方法,給組件帶來了不可見的屬性(props)和狀態(state)。并且Mixin可能會相互依賴,相互耦合,不利于代碼維護
2、不同的Mixin中的方法可能會相互沖突
高階組件
- 定義
高階組件指的是接受一個組件作為參數并返回一個新的組件。高階組件是一個函數,并非一個組件。 - 高階組件的實現方式
1、屬性代理 (Props Proxy)function ppHOC (WrappedComponent) { return class PP extends React.Component { render () { return <WrappedComponent {...this.props} /> } } }
從代碼中我們可以看出高階組件的render方法中,返回被包裹組件。我們把高階組件收到的Props傳遞給他,因此得名Props Proxy
2、反向繼承 (Inheritance Inversion)
function iiHOC(WrappedComponent) {
return class Enhancer extends WrappedComponent {
render() {
return super.render()
}
}
}
如代碼所示,高階組件返回的組件繼承了被包裹組件。
高階組件的作用
我們可以使用高階組件來實現代碼復用,代碼模塊化,邏輯抽象等。還可以進行如下使用
- 操作Props
原理: 傳給WrappedComponent的組件首先都會傳給WrapperComponent,所以我們在WrapperComponent中能對Props進行相應的修改。
代碼:
function ppHOC (WrappedComponent) {
return class PP extends React.Component {
render () {
const nextProps = {
name: 'lta'
}
return <WrappedComponent {...this.props} {...nextProps} />
}
}
}
通過上面的代碼,我們的WrappedComponent組件接收的Props中,就會增加一個name的屬性。
- 抽象state
可以通過向WrappedComponent傳遞Props和回調函數來抽象state
function ppHOC(WrappedComponent) {
return class PP extends React.Component {
constructor(props) {
super(props)
this.state = {
name: ''
}
this.onNameChange = this.onNameChange.bind(this)
}
onNameChange(event) {
this.setState({
name: event.target.value
})
}
render() {
const newProps = {
name: {
value: this.state.name,
onChange: this.onNameChange
}
}
return <WrappedComponent {...this.props} {...newProps}/>
}
}
}
使用方法:
@ppHOC
class Example extends React.Component {
render() {
return <input name="name" {...this.props.name}/>
}
}
通過這種操作是Input編程一個受控組件
- 渲染劫持 (反向繼承)
function iiHOC(WrappedComponent) {
return class Enhancer extends WrappedComponent {
render() {
if (this.props.loggedIn) {
return super.render()
} else {
return null
}
}
}
}
通過該方法可以條件性地渲染組件。
- 與Mixin的區別
高階組件是屬于函數式編程思想,對于被包裹的組件不會感知到高階組件的存在,而高階組件返回的組件能增強原來組件的的功能。Mixin是一種混入模式,會不斷增加組件的方法和屬性,組件本身不僅可以感知,甚至需要處理。一但使用Mixin的地方多時,整個組件就會變得難以維護。