步入React正殿 - React组件设计模式

news/2024/7/15 18:03:56 标签: react.js, 设计模式, 前端

目录

扩展学习资料

高阶组件

@/src/components/hoc/withTooltip.js

@/src/components/hoc/itemA.jsx

@/src/components/hoc/itemB.jsx

@/src/App.js

函数作为子组件【Render pprops】

函数作为子组件

@/src/components/rp/itemC.jsx【父组件】

@/src/components/rp/withTooltip.js【子组件】

练习


扩展学习资料

资料名称

链接

扩展阅读

React组件Render Props VS HOC 设计模式 - 简书

扩展阅读

React Hooks 之于 HoC 与 Render Props - 知乎

高阶组件

复用业务逻辑:判断用户是否是vip:是->有列表,有推荐

一个组件—高阶函数—>新的逻辑的组件

高阶组件是对已有组件的封装形成新的组件之后有自己的状态和逻辑并可以传递已有的组件

const NewComponent = higherOrderComponent(OldComponent)

hoc【higherOrderComponent】

@/src/components/hoc/withTooltip.js

import React from 'react';
// 带工具提示【函数组件】
const withTooltip = (Component) => {
  class HOC extends React.Component {
    state = {
      showToolTip: false,
      content: '',
    };
    handleOver = (event) => {
      this.setState({
        showToolTip: true,
        content: event.target.innerText,
      });
    };
    handleOut = () => {
      this.setState({
        showToolTip: false,
        content: '',
      });
    };
    render() {
      return (
        <div onMouseOver={this.handleOver} onMouseOut={this.handleOut}>
          <Component action={this.state} {...this.props} />
        </div>
      );
    }
  }
  return HOC;
};
export default withTooltip;

@/src/components/hoc/itemA.jsx

import React from 'react';
import withTooltip from './withTooltip';
// 一个简单的带工具提示-业务组件A
const ItemA = (props) => {
  return (
    <div className='container'>
      <button className='btn btn-primary' type='btn'>
        Tooltip A
      </button>
      {props.action.showToolTip && (
        <span className='badge badge-pill badge-primary ml-2'>
          {props.action.content}
        </span>
      )}
    </div>
  );
};
export default withTooltip(ItemA);

@/src/components/hoc/itemB.jsx

import React from 'react';
import withTooltip from './withTooltip';
// 一个简单的带工具提示-业务组件B
const ItemB = (props) => {
  return (
    <div className='container'>
      <button className='btn btn-danger' type='btn'>
        Tooltip B <i>斜体</i>、<b>粗体</b>
      </button>
      {props.action.showToolTip && (
        <span className='badge badge-pill badge-danger ml-2'>
          {props.action.content}
        </span>
      )}
    </div>
  );
};
export default withTooltip(ItemB);

@/src/App.js

import React, { PureComponent } from 'react';
import ItemA from './components/hoc/itemA';
import ItemB from './components/hoc/itemB';
class App extends PureComponent {
    render() {
        console.log('App - rendering');
        return (
          <>
            <ItemA id="1" />
            <ItemB id="2" />
          </>
     	 );
    }
}
export default App;

ItemA,ItemB都需要相同的withTooltip【props.action】显示逻辑,只需要将withTooltip封装就能得到一个将已有组件封装为高阶组件高阶(封装)函数

  • 一个函数,传入一个组件,返回一个新组件
  • 一般不会有UI展现
  • 提供一些可复用的功能

函数作为子组件【Render pprops】

解决复用逻辑的问题

函数作为子组件

 1.定义子组件

// 子组件
render () {
    return (
        <div>
        	{this.props.render(this.state)}
         </div>                
    )
}

2.使用函数作为Props

// 父组件
<RenderPropComponent render={(state)=>(
    <div>
       content
    </div>
)}>

@/src/components/rp/itemC.jsx【父组件】

import React from 'react';
import WithTooltip from './withTooltip';
// 一个简单的带工具提示-业务组件A
const ItemC = (props) => {
  return (
    <div className='container'>
      <WithTooltip
        render={({ showToolTip, content }) => (
          <div>
            <button className='btn btn-primary' type='btn'>
              Tooltip C
            </button>
            {showToolTip && (
              <span className='badge badge-pill badge-primary ml-2'>
                {content}
              </span>
            )}
          </div>
        )}>
        {({ showToolTip, content }) => (
          <div>
            <button className='btn btn-primary' type='btn'>
              Tooltip D
            </button>
            {showToolTip && (
              <span className='badge badge-pill badge-primary ml-2'>
                {content}
              </span>
            )}
          </div>
        )}
      </WithTooltip>
    </div>
  );
};
export default ItemC;

@/src/components/rp/withTooltip.js【子组件】

import React from 'react';
class WithTooltip extends React.Component {
  // // eslint-disable-next-line no-useless-constructor
  // constructor(props) {
  //  super(props);
  // }
  state = {
    showToolTip: false,
    content: '',
  };
  handleOver = (event) => {
    this.setState({
      showToolTip: true,
      content: event.target.innerText,
    });
  };
  handleOut = () => {
    this.setState({
      showToolTip: false,
      content: '',
    });
  };
  render() {
    return (
      <div onMouseOver={this.handleOver} onMouseOut={this.handleOut}>
        {this.props.render && this.props.render(this.state)}
        {this.props.children && this.props.children(this.state)}
      </div>
    );
  }
}
export default WithTooltip;

练习

【题目1】分别使用Render Props和HOC模式实现购物车ToolTips功能;

【题目2】说明Render Props 和 HOC设计模式的优缺点分别是什么;


http://www.niftyadmin.cn/n/4947669.html

相关文章

七月 NFT 行业解读:游戏和音乐 NFT 引领增长,Opepen 掀起热潮

作者&#xff1a;lesleyfootprint.network 2023 年 7 月&#xff0c;NFT 市场的波动性持续存在&#xff0c;交易量呈下降趋势。然而&#xff0c;游戏和音乐 NFT 等领域的增长引人注目。参与这些细分领域的独立用户数量不断增加&#xff0c;反映了这些领域的复苏。 本综合报告…

vue常识

vue是一套用于构建用户界面的渐进式框架,vue的核心库只关注视图层 1.声明式框架 ● 早在jquery的时期,编写代码都是命令式的,命令式框架的特点就是关注过程 ● 声明式框架更加注重结果,命令式的代码封装到了vue.js中,过程靠vue.js来实现 声明式代码更加简单,不需要关注实现,…

vue 项目中 element el-table 表格里 使用slot=“header“ 表头数据用动态变量不更新,用#header可以自动更新

vue 项目中 element el-table 表格里 < template slot“header” slot-scope“scope”> 当使用了 slot“header” 表头数据不能用动态变量&#xff0c;不然不更新。用#header 就可以自动更新 为什么&#xff1f; chatGPT答&#xff1a; 在Vue的<el-table>组件中&a…

图数据库_Neo4j和SpringBoot整合使用_创建节点_删除节点_创建关系_使用CQL操作图谱---Neo4j图数据库工作笔记0009

首先需要引入依赖 springboot提供了一个spring data neo4j来操作 neo4j 可以看到它的架构 这个是下载下来的jar包来看看 有很多cypher对吧 可以看到就是通过封装的驱动来操作graph database 然后开始弄一下 首先添加依赖

opencv进阶07-支持向量机cv2.ml.SVM_create()简介及示例

支持向量机&#xff08;Support Vector Machine&#xff0c;SVM&#xff09;是一种二分类模型&#xff0c;目标是寻找一个标准&#xff08;称为超平面&#xff09;对样本数据进行分割&#xff0c;分割的原则是确保分类最优化&#xff08;类别之间的间隔最大&#xff09;。当数据…

Mybatis批量插入方式有哪些

MyBatis的批量插入有多种写法&#xff0c;下面我将列出一些常见的批量插入写法 方式列表 使用XML配置文件进行批量插入&#xff1a;在XML映射文件中使用<insert>标签&#xff0c;并通过foreach标签迭代批量数据&#xff0c;然后在SQL语句中使用VALUES关键字。使用Java注…

vue-组件库-storybook:理解storybook、实践

一、理解 storybook Storybook是一个开源的工具&#xff0c;可以帮助前端开发者更好地构建、测试和展示组件。 具体来说&#xff0c;Storybook可以做以下几件事情&#xff1a; 1、为每个组件提供一个独立的页面&#xff0c;可以快速展示或调试组件。 2、管理多个组件&#x…

Dubbo之DubboBeanDefinitionParser源码解析

功能概述 Dubbo框架会集成Spring的能力&#xff0c;在以XML方式配置信息时&#xff0c;会用自定义的处理器DubboNamespaceHandler和解析器DubboBeanDefinitionParser对XML进行解析&#xff0c;生成对应的Bean对象和Config对象。 功能分析 DubboBeanDefinitionParser类分析 主…