- 高阶组件是一个函数,接受一个组件作为参数,返回一个新的组件。
- 高阶组件可以用来复用组件逻辑,将组件的状态和行为封装在一个组件中,然后通过高阶组件将其应用到其他组件中。
- 高阶组件可以用来实现组件的组合,将多个组件组合成一个新的组件,从而实现更复杂的逻辑。
我们看下面例子:
import React,{PureComponent} from "react";
// 定义一个高级组件
function hoc(Cpn){
// 1.定义类组件
class NewCpn extends PureComponent{
render(){
return <Cpn name="why" />
}
}
return NewCpn
// 定义函数组件
// function NewCpn2(props){
// }
// return NewCpn2
}
class HelloWorld extends PureComponent{
render(){
return <h1>Hello World</h1>
}
}
const HelloWorldHOC = hoc(HelloWorld)
export class App extends PureComponent{
render(){
return (
<div>
<HelloWorldHOC></HelloWorldHOC>
</div>
)
}
}
export default App
从上面代码中,我们可以看出,高阶组件的作用是将组件的状态和行为封装在一个组件中,然后通过高阶组件将其应用到其他组件中。
定义组件可以使用定义类组件或者定义函数组件,上面代码中function NewCpn2(props){} return NewCpn2
就是定义的函数组件,class NewCpn extends PureComponent{ render(){ return <Cpn name="why" /> } } return NewCpn
是定义的类组件,这两种方式都可以定义高阶组件。
我们可以在元素审核中看到,高阶组件将HelloWorld
组件应用到了HelloWorldHOC
组件中。并且在HelloWorldHOC
组件中,我们可以看到HelloWorld
组件的属性name
的值为why
。
我们看一下浏览器上的效果图:
感谢观看,我们下次见!
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我