高阶组件是参数为组件,返回值为新组件的函数
function hoc(Cpn){
class newCpn extends PureComponent{
}
return newCpn
}
或者
function hoc(Cpn){
function newCpn(props){
}
return newCpn
}
高阶组件相当于是一个组件加工器,将原来的组件输入,输出一个新组件。
import React from "react"
// 高阶组件
function changeCpn(OldCpn) {
class NewCpn extends React.Component {
constructor() {
super()
// 每一个被高阶组件处理的组件都有 name 和 age
this.state = {
name: "lili",
age: 18
}
}
render() {
return <OldCpn { ...this.state } />
}
}
return NewCpn
}
function Home(props) {
return <h1>{props.name}{props.age}</h1>
}
let HomeUpgrade = changeCpn(Home)
class App extends React.Component {
render() {
return (
<div>
<HomeUpgrade />
</div>
)
}
}
export default App
高阶组件给普通组件添加了 state,changeCpn 返回的组件是处理之后的组件。
如果给返回的高级组件传递 props,需要这样接收:
import React from "react"
// 高阶组件
function changeCpn(OldCpn) {
class NewCpn extends React.Component {
constructor(props) {
super()
// 每一个被高阶组件处理的组件都有 name 和 age
this.state = {
name: "lili",
age: 18
}
}
render() {
return <OldCpn { ...this.state } {...this.props} />
}
}
return NewCpn
}
function Home(props) {
return <h1>{props.name}{props.age}{props.addprop}</h1>
}
let HomeUpgrade = changeCpn(Home)
class App extends React.Component {
render() {
return (
<div>
<HomeUpgrade addprop="new" />
</div>
)
}
}
export default App