组件复用&render-props模式&高阶组件

本文探讨了React中组件复用的策略,包括render-props模式和高阶组件(HOC),并详细介绍了它们的实现步骤和注意事项,帮助开发者更好地理解和运用组件状态逻辑的复用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

组件复用

  • 思考:如果两个组件中的部分功能相似或相同,该如何处理?
  • 处理方式:复用相似的功能
    • 复用什么?
    • state
    • 操作state的方法
  • 两种方式:
    • render props模式
    • 高阶组件(HOC)
  • 注意: 这两种方式不是新的API,而是利用React自身特点的编码技巧,演化而成的固定模式

render-props模式

  • 思路:将要复用的state和操作state的方法封装到一个组件中
  • 如何拿到该组件中复用的state
    • 在使用组件时,添加一个值为函数的prop,通过函数参数来获取
      在这里插入图片描述
  • 如何渲染到任意的UI
    • 使用该函数的返回值作为要渲染的UI内容
      在这里插入图片描述

使用步骤

  • 创建Mouse组件,在组件中提供复用的逻辑代码
  • 将要复用的状态作为 props.render(state)方法的参数,暴露到组件外部
  • 使用props.render() 的返回值作为要渲染的内容

在这里插入图片描述

class Mouse extends React.Component {
    // 鼠标位置状态
    state = {
        x: 0,
        y: 0
    }

    // 监听鼠标移动事件
    componentDidMount(){
        window.addEventListener('mousemove',this.handleMouseMove)
    }
    handleMouseMove = e => {
        this.setState({
            x: e.clientX,
            y: e.clientY
        })
    }
    render(){
        // 向外界提供当前子组件里面的数据
        return this.props.render(this.state)
    }
}
class App extends React.Component {
    render() {
        return (
            <div>
                App
                <Mouse render={mouse => {
                    return <p>X{mouse.x}Y{mouse.y}</p>
                }}/>
            </div>
        )
    }
}
ReactDOM.render(<App />,document.getElementById('root'))

children代替render属性

  • 注意:并不是该模式叫 render props就必须使用名为render的prop,实际上可以使用任意名称的prop
  • 把prop是一个函数并且告诉组件要渲染什么内容的技术叫做: render props模式
  • 推荐:使用childre代替render属性
    在这里插入图片描述

优化代码

推荐给render props模式添加props校验
在这里插入图片描述

高阶组件

  • 目的:实现状态逻辑复用
  • 采用 包装模式
  • 手机:获取保护功能
  • 手机壳:提供保护功能
  • 高阶组件就相当于手机壳,通过包装组件,增强组件功能
  • 高阶组件(HOC、Higher-Order Component) 是一个函数,接收要包装的组件,返回增强后的组件
    在这里插入图片描述
  • 高阶组件内部创建了一个类组件,在这个类组件中提供复用的状态逻辑代码,通过prop将复用的状态传递给被包装组件WrappedComponent
    在这里插入图片描述

使用步骤

  • 创建一个函数,名称约定以with开头
  • 指定函数参数,参数应该以大写字母开头
  • 在函数内部创建一个类组件,提供复用的状态逻辑代码,并返回
  • 在该组件中,渲染参数组件,同时将状态通过prop传递给参数组件
  • 调用该高阶组件,传入要增强的组件,通过返回值拿到增强后的组件,并将其渲染到页面

包装函数

// 定义一个函数,在函数内部创建一个相应类组件
function withMouse(WrappedComponent) {
    // 该组件提供复用状态逻辑
    class Mouse extends React.Component {
        state = {
            x: 0,
            y: 0
        }
        // 事件的处理函数
        handleMouseMove = (e) => {
            this.setState({
                x: e.clientX,
                y: e.clientY
            })
        }
        // 当组件挂载的时候进行事件绑定
        componentDidMount() {
            window.addEventListener('mousemove', this.handleMouseMove)
        }
        // 当组件移除时候解绑事件
        componentWillUnmount() {
            window.removeEventListener('mousemove', this.handleMouseMove)
        }
        render() {
            // 在render函数里面返回传递过来的组件,把当前组件的状态设置进去
            return <WrappedComponent {...this.state} />
        }
    }
    return Mouse
}

加强组件

function Position(props) {
    return (
        <p>
            X:{props.x}
            Y:{props.y}
        </p>
    )
}
// 把position 组件来进行包装
let MousePosition = withMouse(Position)

class App extends React.Component {
    constructor(props) {
        super(props)
    }
    render() {
        return (
            <div>
                高阶组件
                <MousePosition></MousePosition>
            </div>
        )
    }
}

设置displayName

  • 使用高阶组件存在的问题:得到两个组件的名称相同
  • 原因:默认情况下,React使用组件名称作为displayName
  • 解决方式:为高阶组件设置displayName,便于调试时区分不同的组件
  • displayName的作用:用于设置调试信息(React Developer Tools信息)
  • 设置方式:
    在这里插入图片描述

传递props

  • 问题:如果没有传递props,会导致props丢失问题
  • 解决方式: 渲染WrappedComponent时,将state和props一起传递给组件
    在这里插入图片描述

小结

  • 组件通讯是构建React应用必不可少的一环
  • props的灵活性让组件更加强大
  • 状态提升是React组件的常用模式
  • 组件生命周期有助于理解组件的运行过程
  • 钩子函数让开发者可以在特定的时机执行某些功能
  • render props 模式和高阶组件都可以实现组件状态逻辑的复用
  • 组件极简模型: (state,props) => UI

高阶组件装饰器写法

高阶组件装饰器写法

npm install --save-dev babel-plugin-transform-decorators-legacy
const { injectBabelPlugin } = require('react-app-rewired')
module.exports = function override(config) {
 config = injectBabelPlugin(
 ['import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }],
  config,
)
 config = injectBabelPlugin(
 ['@babel/plugin-proposal-decorators', { "legacy": true }],
  config,
)
 return config
}

使用装饰器

import React, { Component } from 'react'
import {Button} from 'antd'
const withKaikeba = (Component) => {
 const NewComponent = (props) => {
  return <Component {...props} name="开课吧高阶组件" />;
};
 return NewComponent;
};
const withLog = Component=>{
 class NewComponent extends React.Component{
  render(){
   return <Component {...this.props} />;
 }
  componentDidMount(){
   console.log(Component.name ,'didMount',this.props)
 }
}
 return NewComponent
}
@withKaikeba
@withLog
class App extends Component {
 render() {
  return (
   <div className="App">
   <h2>hi,{this.props.name}</h2>
    <Button type="primary">Button</Button>
   </div>
 )
}
}
export default App

组件复合

类似于vue的slot,props.children相当于匿名插槽,props.footer相当于命名插槽
在这里插入图片描述在这里插入图片描述

props.children可以是jsx也可以是一个函数相当于作用域插槽

在这里插入图片描述
在这里插入图片描述

过滤children

在这里插入图片描述
在这里插入图片描述
this.props.children 的值有三种可能:如果当前组件没有子节点,它就是 undefined ;如果有一个子节点,数据类型是 object ;如果有多个子节点,数据类型就是 array 。所以,处理 this.props.children 的时候要小心。

React 提供一个工具方法 React.Children 来处理 this.props.children 。我们可以用 React.Children.map 来遍历子节点,而不用担心 this.props.children 的数据类型是 undefined 还是 object。


object React.Children.map(object children, function fn [, object context])
 
使用方法:
React.Children.map(this.props.children, function (child) {
    return <li>{child}</li>;
})
React.Children.forEach()
  跟React.Children.map()一样,区别在于无返回。


React.Children.count()
  React.Children.count()用来计数,返回child个数,和传递给 map 或者 forEach 的回调函数的调用次数一致。


React.Children.only()
  验证children里只有唯一的孩子并返回他。否则这个方法抛出一个错误。


React.Children.toArray()
  将children转换成Array,对children排序时需要使用.如果不用React.Children.toArray()方法,直接写children.sort()就会报错
function Father({children}) {
    let children1 = React.Children.toArray(children);
    return(
      <div>
      {children1.sort().join(' ')}
      </div>    
    )        
 }


<Father>
    {'ccc'}
    {'aaa'}
    {'bbb'}
</Father>//渲染结果: aaa bbb ccc

修改children

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值