react 高阶组件

高阶组件的概念来自于高阶函数————可以接受函数作为参数/返回值的函数。

高阶组件就是可以接受组件作为参数,返回组件的函数。

用法很多,不过可读性较差。

一般会这样用:

实现判断权限,决定返回什么组件。

实现数据处理之后再传递给(要被返回的)组件。

实现装饰器模式的功能。

实现数据请求和组件的分离。

复制代码
import React from 'react';
import ReactDom from 'react-dom';

function decorator (comp: React.FC<ComponentProps>) { 
  // 返回组件
return class newComp extends React.Component<ComponentProps, State>{ state = { value: this.props.something.toUpperCase()} render() { return <comp value={this.state.value} /> } } } const myInput = (props: ComponentProps) =>{ return <input defaultValue={props.value} /> }

// 组件参数
newComp = decorator(myInput) 
ReactDom.render(<newComp something={'something'}/>, document.querySelector('#id'))
复制代码

 

posted @   Esther_Cheung  阅读(133)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示