React组件复用的两种方式:render-props模式和高阶组件(HOC)

1,475 阅读5分钟

思路:将要复用的state 和 操作state的方法(组件复用逻辑)封装到一个组件中

这两种方式不是新的API,而是利用React自身特点的编码技巧,演化而成的固定模式

render props模式

思路分析

  • 如何拿到封装好的组件中复用的state

    • 在使用组件时,添加一个值为函数的prop,通过函数参数来获取(需要组件内部实现) 👇:prop的取名为render render-props-01.png
  • 如何渲染到任意的UI

    • 使用该函数的返回值作为要渲染的UI内容(需要组件内部实现) render-props-02.png

使用步骤

  • 创建Mouse组件,在组件中提供复用的逻辑代码
  • 将要复用的状态作为 props.render(state)方法的参数,暴露到组件外部
  • 使用props.render() 的返回值作为要渲染的内容 render-props模式-01.png
import React from 'react'
import ReactDOM from 'react-dom'
// 导入图片资源
import img from './images/cat.png'

// 创建Mouse组件
class Mouse extends React.Component {
  // 鼠标位置state  👉“要复用的state”
  state = {
    x: 0,
    y: 0
  }

  // 鼠标移动事件的事件处理程序  👉 “操作state的方法”
  handleMouseMove = e => {
    this.setState({
      x: e.clientX,
      y: e.clientY
    })
  }

  // 监听鼠标移动事件
  componentDidMount() {
    window.addEventListener('mousemove', this.handleMouseMove)
  }
  
  //将要复用的状态作为props.render()方法的参数,暴露到组件外部
  render() {
    return this.props.render(this.state)  // 向外界提供当前子组件里面的数据
  }
}

class App extends React.Component {
  //使用props.render()的返回值作为要渲染的内容
  render() {
    return (
      <div>
        <h1>render props 模式</h1>
        <Mouse
          render={mouse => {  //mouse就是上面的this.state
            return (
              <p>
                鼠标位置:{mouse.x} {mouse.y}
              </p>
            )
          }}
        />
        
        {/* 猫捉老鼠 */}
        <Mouse
          render={mouse => {
            return (
              <img
                src={img}
                alt="猫"
                style={{
                  position: 'absolute',
                  top: mouse.y - 64,
                  left: mouse.x - 64
                }}
              />
            )
          }}
        />
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

children代替render属性

  • 注意:并不是该模式叫 render props就必须使用名为render的prop,实际上可以使用任意名称的prop
  • 把prop是一个函数并且告诉组件要渲染什么内容的技术叫做: render props模式
  • 推荐:使用childre代替render属性 render-props-children模式.png
import React from 'react'
import ReactDOM from 'react-dom'

/* 
  render props 模式
*/
import PropTypes from 'prop-types'
import img from './images/cat.png'

class Mouse extends React.Component {
  // 鼠标位置state
  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() {
    return this.props.children(this.state)
  }
}

// 添加props校验
Mouse.propTypes = {
  children: PropTypes.func.isRequired
}

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>render props 模式</h1>
        <Mouse>
          {mouse => {
            return (
              <p>
                鼠标位置:{mouse.x} {mouse.y}
              </p>
            )
          }}
        </Mouse>

        <Mouse>
          {mouse => (
            <img
              src={img}
              alt="猫"
              style={{
                position: 'absolute',
                top: mouse.y - 64,
                left: mouse.x - 64
              }}
            />
          )}
        </Mouse>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))


优化代码

1.推荐给render props模式添加props校验 优化-添加校验.png 2. 应该在组件卸载时解除mousemove事件绑定 优化-移除事件绑定.png

高阶组件 (★★★)

  • 采用 包装模式
  • 高阶组件就相当于手机壳,通过包装组件,增强组件功能

思路分析

  • 高阶组件(HOC、Higher-Order Component) 是一个函数,接收要包装的组件(参数WrappedComponent),返回增强后的组件

高阶组件-函数.png

  • 高阶组件内部创建了一个类组件,在这个类组件中提供复用的状态逻辑代码,通过prop将复用的状态传递给被包装组件WrappedComponent

高阶组件-类组件内部实现.png

使用步骤

  • 创建一个函数,名称约定以with开头
  • 指定函数参数,参数应该以大写字母开头(组件名是以大写开头的)
  • 在函数内部创建一个类组件,提供复用的状态逻辑代码,并返回
  • 在该组件中,渲染参数组件(该类组件只提供状态逻辑,UI结构由传入的参数组件决定),同时将状态通过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函数里返回参数组件,把当前组件的状态设置进去,参数组件就可以通过props接收到当前类组件中复用的状态
            return <WrappedComponent {...this.state} />  
        }
    }
    return Mouse
}

哪个组件需要加强,通过调用withMouse这个函数,然后把返回的值设置到父组件中即可

function Position(props) {   // 在参数组件里可以通过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

  • 使用高阶组件存在的问题:得到两个组件的名称相同,都叫Mouse(函数里的类组件名)
  • 原因:默认情况下,React使用函数里类组件的名称作为displayName
  • 解决方式:为高阶组件设置displayName,便于调试时区分不同的组件
  • displayName的作用:用于设置调试信息(React Developer Tools信息) 拼接了组件名:'...',使用getDisplayName:优先返回dispalyName、或(参数)组件名,或返回'Component' 高阶组件-displayName.png
import React from 'react'
import ReactDOM from 'react-dom'

/* 
  高阶组件
*/

import img from './images/cat.png'

// 创建高阶组件
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() {
      return <WrappedComponent {...this.state} />
    }
  }

  // 设置displayName(拼接字符串)
  Mouse.displayName = `WithMouse${getDisplayName(WrappedComponent)}`

  return Mouse
}

function getDisplayName(WrappedComponent) {  //WrappedComponent.name获取到的是'Position'、'Cat'
  return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}

// 用来测试高阶组件
const Position = props => (
  <p>
    鼠标当前位置:(x: {props.x}, y: {props.y})
  </p>
)

// 猫捉老鼠的组件:
const Cat = props => (
  <img
    src={img}
    alt=""
    style={{
      position: 'absolute',
      top: props.y - 64,
      left: props.x - 64
    }}
  />
)

// 获取增强后的组件:
const MousePosition = withMouse(Position)

// 调用高阶组件来增强猫捉老鼠的组件:
const MouseCat = withMouse(Cat)

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>高阶组件</h1>
        {/* 渲染增强后的组件 */}
        <MousePosition />
        <MouseCat />
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

传递props

  • 问题:高阶组件没有往下传递props,导致props丢失
  • 解决方式: 渲染WrappedComponent时,将state和props一起传递给组件

传递props.png

import React from 'react'
import ReactDOM from 'react-dom'

/* 
  高阶组件
*/

// 创建高阶组件
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() {
      console.log('Mouse:', this.props)
      return <WrappedComponent {...this.state} {...this.props} />  //需要把props传给组件
    }
  }

  // 设置displayName
  Mouse.displayName = `WithMouse${getDisplayName(WrappedComponent)}`

  return Mouse
}

function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}

// 用来测试高阶组件
const Position = props => {
  console.log('Position:', props)
  return (
    <p>
      鼠标当前位置:(x: {props.x}, y: {props.y})
    </p>
  )
}

// 获取增强后的组件:
const MousePosition = withMouse(Position)

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>高阶组件</h1>
        <MousePosition a="1" />  {/*相当于给高阶组件的类组件Mouse添加的props*/}
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

辅助理解组件:

(state,props) => UI 组件内部提供状态,接收到外部传入的props,渲染出UI