React中的几种逻辑复用方式

React class render props

mouse-position.js

import React, { Component } from 'react'

class MousePosition extends Component {
  constructor(props) {
    super(props)
    this.state = {
      x: 0,
      y: 0
    }
  }

  handleMouseMove = (e) => {
    const { clientX, clientY } = e
    this.setState({
      x: clientX,
      y: clientY
    })
  }

  componentDidMount() {
    document.addEventListener('mousemove', this.handleMouseMove)
  }

  componentWillUnmount() {
    document.removeEventListener('mousemove', this.handleMouseMove)
  }

  render() {
    const { children } = this.props
    const { x, y } = this.state
    return(
      <div>
        {
          children({x, y})
        }
      </div>
    )
  }
}

app.js

import React from "react";
import MousePosition from "./mouse-position";

export default function App() {
  return (
    <div className="App">
      <MousePosition>
        {({ x, y }) => {
          return (
            <div>
              <p>
                x:{x}, y: {y}
              </p>
            </div>
          );
        }}
      </MousePosition>
    </div>
  );
}

React Hoc

mouse-position.js

import React from "react";

const MousePosition = (Component) => {
  class MousePositionComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        x: 0,
        y: 0
      };
    }

    handleMouseMove = (e) => {
      const { clientX, clientY } = e;
      this.setState({
        x: clientX,
        y: clientY
      });
    };

    componentDidMount() {
      document.addEventListener("mousemove", this.handleMouseMove);
    }

    componentWillUnmount() {
      document.removeEventListener("mousemove", this.handleMouseMove);
    }

    render() {
      const { x, y } = this.state;
      return <Component x={x} y={y} />;
    }
  }
  return MousePositionComponent;
};

export default MousePosition;

app.js

import React from "react";
import MousePosition from "./mouse-position";

function App({ x, y }) {
  return (
    <div>
      <p>
        x:{x}, y: {y}
      </p>
    </div>
  );
}

export default MousePosition(App);

React Hooks

use-position.js

import { useState, useEffect } from "react";

const usePosition = () => {
  const [position, setPosition] = useState({
    x: 0,
    y: 0
  });

  const handleMouseMove = (e) => {
    const { clientX, clientY } = e;
    setPosition({ x: clientX, y: clientY });
  };

  useEffect(() => {
    window.addEventListener("mousemove", handleMouseMove);
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
    };
  }, []);

  return position;
};

export default usePosition;

app.js

import React from "react";
import usePosition from "./use-position";

export default function App() {
  const position = usePosition();
  return (
    <div>
      <p>
        x:{position.x},y:{position.y}
      </p>
    </div>
  );
}
posted @ 2022-11-17 17:18  小菜菜爱吃菜  阅读(81)  评论(0编辑  收藏  举报