- 高阶组件是一个函数,接收一个组件作为参数,返回一个新的组件。
- 高阶组件可以用来增强组件的功能,比如添加props,添加生命周期方法,添加ref等等。
- 高阶组件可以用来复用组件的逻辑,比如添加loading,添加错误处理等等。
- 高阶组件可以用来实现组件的组合,比如添加样式,添加动画等等。
我们看下面例子:
import React,{PureComponent} from "react";
import enhanceUserInfo from "./hoc/enhanced_props";
import About from './pages/About';
const Home = enhanceUserInfo(function(props){
return <h1>Home:{props.name}-{props.level}-{props.banners}</h1>
})
const Profile = enhanceUserInfo(function(props){
return <h1>Profile:{props.name}-{props.level}</h1>
})
const HelloFriend = enhanceUserInfo(function(props){
return <h1>HelloFriend:{props.name}-{props.level}</h1>
})
export class App extends PureComponent{
render(){
return (
<div>
<Home banners={["轮播1","轮播2"]}></Home>
<Profile></Profile>
<HelloFriend></HelloFriend>
<About></About>
</div>
)
}
}
export default App
从上面代码中,我们可以看出,高阶组件的作用是增强组件的功能,比如添加props,添加生命周期方法,添加ref等等。
我们先看一下hock的代码(enhanced_props
):
enhanced_props.jsx
import { PureComponent } from "react";
// 定义组件:给一些需要特殊数据的组件,注入props
function enhanceUserInfo(OriginComponent){
class NewComponent extends PureComponent{
constructor(props){
super(props)
this.state = {
userInfo:{
name:"hello",
level:99
}
}
}
render(){
return <OriginComponent {...this.props} {...this.state.userInfo} />
}
}
return NewComponent
}
export default enhanceUserInfo
从enhanced_props.js
中,我们可以看出,高阶组件的作用是增强组件的功能,比如添加props,添加生命周期方法,添加ref等等。
我们可以在元素审核中看到,高阶组件将Home
组件应用到了enhanced_props
增强函数中。并且在enhanced_props
增强函数中,我们可以看到Home
组件的属性name
的值为hello
,level
的值为99
。 banners
的值为["轮播1","轮播2"]
。
同理,Profile
组件和HelloFriend
组件也应用到了enhanced_props
增强函数中。并且在enhanced_props
增强函数中,我们可以看到Profile
组件的属性name
的值为hello
,level
的值为99
。
在HelloFriend
组件中,我们可以看到HelloFriend
组件的属性name
的值为hello
,level
的值为99
。
About
组件的属性name
的值为why
。
About组件
我们先看一下About
组件的代码:
import React,{PureComponent} from "react";
import enhanceUserInfo from "../hoc/enhanced_props";
export class About extends PureComponent{
render(){
return (
<div>About:{this.props.name}</div>
)
}
}
export default enhanceUserInfo(About)
从上面代码中,我们可以看出,About
组件的属性name
的值为hello
。 但是我们并没有在About
组件中传递任何props给enhanceUserInfo
函数。这是因为我们在调用enhanceUserInfo
函数时,将About
组件作为参数传递给了enhanceUserInfo
函数。
banners
的值为undefined
。 Profile
组件的属性name
的值为why
。 banners
的值为undefined
。 HelloFriend
组件的属性name
的值为why
。 banners
的值为undefined
。
最后我们看一下浏览器上的效果图:
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我