react——props和高阶组件

658 阅读2分钟

前言

今天我们一起看看 react中的props模式和高阶组件相关内容,看看这两个解决了什么样的问题,我们应该怎样书写我们的代码呢?


一、render props 模式

1. react复用概述

如何复用相似的功能?

组件状态逻辑,1. state 2. 操作state的方法 两种实现方案:1. render props模式 2. 高阶组件(HOC) 注意:这两种方式不是新的API,而是利用React自身特点的编码技巧,演化而成的固定模式(写法),可以归结 为我们常说的“设计模式”。俗话说的好“世上本没有路,走的人多了也就成了路”

2. render props 模式

将要复用的state和操作state的方法封装到一个组件中

对组件外暴露state和操作state的方法(子组件向父组件传递数据)

render() {
  return (
    <div>
      {/*对外暴露了,组件状态和操作组件状态的方法*/}
      {this.props.render(this.state.count, this.handleCount)}
    </div>
  )
}

调用父组件传递进来的函数,把state和操作state的方法作为函数参数传递进去

<div>
  <Counter
   render={(count, handleCount) => {
     return <button onClick={handleCount}> 我被点击了{count}次</button>;
   }}
  />
  <Counter
   render={(count, handleCount) => {
     return <h1onMouseOver={handleCount}> 标题划过了{count}次</h1>;
   }}
  />
</div>

3. children 代替 render 属性

注意:并不是该模式叫 render props 就必须使用名为render的prop,实际上可以使用任意名称的prop 把prop是一个函数并且告诉组件要渲染什么内容的技术叫做:render props模式

推荐:使用 children 代替 render 属性

<Counter>
  {({count, handleCount}) => <button onClick={handleCount}>我被点击了{count}次</button> }
</Counter>
// 组件内部:
this.props.children(this.state.count, this.state.handleCount)
// Context 中的用法:
<Consumer>
  {data => <span>data参数表示接收到的数据 -- {data}</span>}
</Consumer>

二、高阶组件

1. 概述

目的:实现状态逻辑复用

高阶组件(HOC,Higher-Order Component)是一个函数,接收要包装的组件,返回增强后的组件 高阶组件内部创建一个类组件,在这个类组件中提供复用的状态逻辑代码,通过prop将复用的状态传递给 被包装组件 WrappedComponent

const EnhancedComponent = withCounter(WrappedComponent)
// 高阶组件内部创建的类组件:
class Counter extends React.Component {
  render() {
    return <WrappedComponent count={this.state.count}, handleCount={this.handleCount} />
  }
}

2. 使用步骤

  • 创建一个函数,名称约定以 with 开头
  • 指定函数参数,参数应该以大写字母开头(作为要渲染的组件)
  • 在函数内部创建一个类组件,提供复用的状态逻辑代码,并返回此组件
  • 在该组件中,渲染参数组件,同时将状态通过prop传递给参数组件
  • 调用该高阶组件,传入要增强的组件,通过返回值拿到增强后的组件,并将其渲染到页面中
function withCounter(WrappedComponent) { 
  class Counter extends React.Component {} 
  return Counter
}
// 在render方法中:
return <WrappedComponent count={this.state.count}, handleCount={this.handleCount} />

3. 传递props

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

<WrappedComponent {...this.state} {...this.props} />

总结

Don't put off till tomorrow what should be done today.