React 第二十一章 Render Props

React 中,常见有两种方式来进行横切关注点的抽离:

  • 高阶组件(HOC
  • Render Props

React Render Props是React中一种常见的组件复用模式,用于将组件的渲染逻辑与组件的状态逻辑分离开来。Render Props模式允许一个组件通过在props中传递一个函数来控制另一个组件的渲染。

Render Props 实际上并非什么新语法,而是指一种在 React 组件之间使用一个值为函数的 prop 共享代码的简单技术。

使用Render Props模式有以下几个优点:

  1. 组件复用:通过将渲染逻辑封装在一个函数中,多个组件可以共享同一个渲染逻辑,避免代码冗余。
  2. 灵活性:Render Props模式允许父组件决定子组件的渲染方式,子组件可以根据父组件传递的函数来自定义渲染内容,提供了更大的灵活性和可定制性。
  3. 数据共享:通过Render Props,父组件可以将自己的状态或其他数据传递给子组件,实现了数据共享的目的。

如何使用 Render Props

我们首先还是来看一个示例:

// App.jsx
import ChildCom1 from "./components/ChildCom1"
import ChildCom2 from "./components/ChildCom2"

function App() {
  return (
    <div style={{
      display: 'flex',
      justifyContent: 'space-between',
      width: "850px"
    }}>
      <ChildCom1 />
      <ChildCom2 />
    </div>
  );
}

export default App;
// components/ChildCom1.jsx
import { useState } from 'react';

function ChildCom1() {

    const [points, setPoints] = useState({
        x: 0,
        y: 0
    })

    function handleMouseMove(e) {
        setPoints({
            x: e.clientX,
            y: e.clientY
        })
    }

    return (
        <div style={{
            width: '400px',
            height: '400px',
            backgroundColor: 'red'
        }} onMouseMove={handleMouseMove}>
            <h1>移动鼠标!</h1>
            <p>当前的鼠标位置是 ({points.x}, {points.y})</p>
        </div>
    );
}

export default ChildCom1;
// components/ChildCom2.jsx

import { useState } from 'react';

function ChildCom2() {

    const [points, setPoints] = useState({
        x: 0,
        y: 0
    })

    function handleMouseMove(e) {
        setPoints({
            x: e.clientX,
            y: e.clientY
        })
    }

    return (
        <div style={{
            width: '400px',
            height: '400px',
            backgroundColor: 'grey',
            position: 'relative',
            overflow: 'hidden'
        }} onMouseMove={handleMouseMove}>
            <h1>移动鼠标!</h1>
            {/* 这里减去 460 是因为要减去左边 div 的宽度 + 两个大 div 之间 50 的间距 */}
            <div style={{
                width: '15px',
                height: '15px',
                borderRadius: "50%",
                backgroundColor: 'white',
                position: 'absolute',
                left: points.x - 5 - 460,
                top: points.y - 5 - 10,
            }}></div>
        </div>
    );
}

export default ChildCom2;

在上面的代码中,App 根组件下渲染了两个子组件,这两个子组件一个是显示鼠标的位置,另外一个是根据鼠标位置显示一个追随鼠标移动的小球。

仔细观察代码,你会发现这两个子组件内部的逻辑基本上是一模一样的,只是最终渲染的内容不一样,此时我们就可以使用 Render Props 对横切关注点进行一个抽离。

方式也很简单,就是在一个组件中使用一个值为函数的 prop,函数的返回值为要渲染的视图。

// /components/MouseMove.jsx

import { useState } from 'react';

function MouseMove(props) {
    const [points, setPoints] = useState({
        x: 0,
        y: 0
    })

    function handleMouseMove(e) {
        setPoints({
            x: e.clientX,
            y: e.clientY
        })
    }

    return (
        props.render ? props.render({ points, handleMouseMove }) : null
    );
}

export default MouseMove;

在上面的代码中,我们新创建了一个 MouseMove 组件,该组件就封装了之前 ChildCom1ChildCom2 组件的公共逻辑。该组件的 props 接收一个名为 render 的参数,只不过该参数对应的值为一个函数,我们调用时将对应的状态和处理函数传递过去,该函数的调用结果为返回一段视图。

import ChildCom1 from "./components/ChildCom1";
import ChildCom2 from "./components/ChildCom2";
import MouseMove from "./components/MouseMove";

function App() {
  return (
    <div style={{
      display: 'flex',
      justifyContent: 'space-between',
      width: "850px"
    }}>
      <MouseMove render={props => <ChildCom1 {...props} />} />
      <MouseMove render={props => <ChildCom2 {...props} />} />
    </div>
  );
}

export default App;

接下来在 App 根组件中,我们使用 MouseMove 组件,该组件上有一个 render 属性,对应的值就是函数,函数返回要渲染的组件。

function ChildCom1(props) {
    return (
        <div style={{
            width: '400px',
            height: '400px',
            backgroundColor: 'red'
        }} onMouseMove={props.handleMouseMove}>
            <h1>移动鼠标!</h1>
            <p>当前的鼠标位置是 ({props.points.x}, {props.points.y})</p>
        </div>
    );
}

export default ChildCom1;
function ChildCom2(props) {
    return (
        <div style={{
            width: '400px',
            height: '400px',
            backgroundColor: 'grey',
            position: 'relative',
            overflow: 'hidden'
        }} onMouseMove={props.handleMouseMove}>
            <h1>移动鼠标!</h1>
            {/* 这里减去 460 是因为要减去左边 div 的宽度 + 两个大 div 之间 50 的间距 */}
            <div style={{
                width: '15px',
                height: '15px',
                borderRadius: "50%",
                backgroundColor: 'white',
                position: 'absolute',
                left: props.points.x - 5 - 460,
                top: props.points.y - 5 - 10,
            }}></div>
        </div>
    );
}

export default ChildCom2;

最后就是子组件 ChildCom1ChildCom2 的改写,可以看到这两个子组件就只需要书写要渲染的视图了。公共的逻辑已经被 MouseMove 抽取出去了。

另外需要说明的是,虽然这个技巧的名字叫做 Render Props,但不是说必须要提供一个名为 render 的属性。事实上,封装公共逻辑的组件(例如上面的 MouseMove)只要能够得到要渲染的视图即可,所以传递的方式可以有多种。

例如:

import ChildCom1 from "./components/ChildCom1";
import ChildCom2 from "./components/ChildCom2";
import MouseMove from "./components/MouseMove";

function App() {
  return (
    <div style={{
      display: 'flex',
      justifyContent: 'space-between',
      width: "850px"
    }}>
      <MouseMove>
        {(props) => <ChildCom1 {...props} />}
      </MouseMove>
      <MouseMove>
        {props => <ChildCom2 {...props} />}
      </MouseMove>
    </div>
  );
}

export default App;

上面使用 MouseMove 组件时,并没有传递什么 render 属性,而是通过 props.children 的形式将要渲染的视图传递到了组件内部。

MouseMove 组件内部,就不再是执行 render 方法了,而是应该执行 props.children,如下:

props.children ? props.children({ points, handleMouseMove }) : null

何时使用 Render Props

同样是作为抽离横切关注点,前面所讲的 HOC 也能做到相同的效果。例如我们可以将上面的示例修改为 HOC 的方式。

// HOC/withMouseMove.js

import { useState } from "react";
function withMouseMove(Com) {
  // 返回一个新组件
  return function NewCom() {
    const [points, setPoints] = useState({
      x: 0,
      y: 0,
    });
    function handleMouseMove(e) {
      setPoints({
        x: e.clientX,
        y: e.clientY,
      });
    }

    const mouseHandle = { points, handleMouseMove };
    return <Com {...mouseHandle} />;
  };
}

export default withMouseMove;
// App.jsx

import ChildCom1 from "./components/ChildCom1";
import ChildCom2 from "./components/ChildCom2";
import withMouseMove from "./HOC/withMouseMove"

const NewChildCom1 = withMouseMove(ChildCom1);
const NewChildCom2 = withMouseMove(ChildCom2);

function App() {
  return (
    <div style={{
      display: 'flex',
      justifyContent: 'space-between',
      width: "850px"
    }}>
      <NewChildCom1 />
      <NewChildCom2 />
    </div>
  );
}

export default App;

一般来讲,Render Props 应用于组件之间功能逻辑完全相同,仅仅是渲染的视图不同。这个时候我们可以通过 Render Props 来指定要渲染的视图是什么。

HOC 一般是抽离部分公共逻辑,也就是说组件之间有一部分逻辑相同,但是各自也有自己独有的逻辑,那么这个时候使用 HOC 比较合适,可以在原有的组件的基础上做一个增强处理。

  • 17
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值