react高阶组件
高阶组件为了提高组件复用性,在react中就有了HOC(Higher-Order Component)的概念。所谓的高阶组件,其本质依旧是组件,只是它返回另外一个组件,产生新的组件可以对属性进行包装,也可以重写部分生命周期。 首先看一下简单的例子:在components文件夹下新建Hoc.js组件文件,并在index.js中引入该组件。 Hoc.js import React,{ Component } from "react"; function test(props){ return ( <div>{props.stage} - {props.name}</div> ) } const withName = Comp => { return props => <Comp {...props} name="高阶组件试用" /> } export default withName(test) index.js 上面例子中的widthName组件就是一个高阶组件,接收了一个组件,为该组件传递一个name参数后,返回扩展以后的组件,这就是高阶组件的用法。 ?重写生命周期当我们需要在高阶组件的某个生命周期里面获取数据或者做其他的操作的时候,可以使用高阶组件重写生命周期。 ?Hoc.js import React,{ Component } from "react"; function test(props){ return ( <div>{props.stage} - {props.name}</div> ) } const withName = Comp => { class NewComponent extends Component{ componentDidMount(){ console.log(‘高阶组件重写生命周期‘); } render(){ return <Comp {...this.props} name="高阶组件试用" /> } } return NewComponent } export default withName(test) 高阶组件链式调用import React,{ Component } from "react"; function test(props){ return ( <div>{props.stage} - {props.name}</div> ) } const withName = Comp => { class NewComponent extends Component{ componentDidMount(){ console.log(‘高阶组件重写生命周期‘); } render(){ return <Comp {...this.props} name="高阶组件试用" /> } } return NewComponent } const widthLog = Comp => { console.log(Comp.name + ‘渲染了‘); return props => <Comp {...props} /> } export default widthLog(withName(test)) ?高阶组件装饰器写法在上面的高阶组件链式调用的时候,我们使用的嵌套的写法,这种写法很不直观,因此可以借助ES7里面的装饰器来处理这种问题。 首先,需要在项目根目录执行安装命令: npm install --save-dev babel-plugin-transform-decorators-legacy 其次,修改config-overrides.js 然后,重启项目后改造上面的高阶组件: 1,将连个高阶组件移动到需要改造的test组件上面; 2,在需要改造的test组件前面依次调用两个高阶组件; 3,将需要改造的test组件由函数组件改为class类组件; import React,{ Component } from "react"; const withName = Comp => { class NewComponent extends Component{ componentDidMount(){ console.log(‘高阶组件重写生命周期‘); } render(){ return <Comp {...this.props} name="高阶组件试用" /> } } return NewComponent } const withLog = Comp => { console.log(Comp.name + ‘渲染了‘); return props => <Comp {...props} /> }; @withName @withLog class test extends Component{ render(){ return ( <div>{this.props.stage} - {this.props.name}</div> ) } } export default test ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- XML与JSON 区别
- 对XML的理解
- react-native – 无法在native native中添加border bottom
- PostgreSQL INSERT ON CONFLICT UPDATE(upsert)使用所有排除
- OGG 有for Oracle database 10g and Linux Itanium CPU 版本
- $.getJSON和PHP文件
- objective-c – 使用KVC分配给SEL类型的属性
- quick-cocos2d-x scheduler
- c – 如何通过引用对用户定义对象的类型集(STL)的数组元素进
- ruby-on-rails – Rails服务器无法运行 – 找不到gem错误