使用React Hooks重写Render Props复用鼠标位置例子

266 阅读1分钟

具体Hooks的用法可以参考React Hooks 入门教程 - 阮一峰的网络日志 (ruanyifeng.com)

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./index.css";
import reportWebVitals from "./reportWebVitals";
import img from "./images/cat.jfif";

function Parent() {
  const renderText = (mouse) => {
    return <p>Mouse Position: {mouse.x + " " + mouse.y}</p>;
  };

  const renderPic = (mouse) => {
    return (
      <img
        alt="cat"
        style={{ position: "absolute", top: mouse.y, left: mouse.x }}
        src={img}
      ></img>
    );
  };
  return (
    <div>
      <h1>Render Props with Hooks</h1>
      <Mouse>{renderText}</Mouse>
      <Mouse>{renderPic}</Mouse>
    </div>
  );
}

function Mouse(props) {
  // 加入state
  const [pos, setPos] = useState({ x: 0, y: 0 });

  // 副作用用来注册和移除事件,只需要执行一次
  useEffect(() => {
    const f = (e) => setPos({ x: e.clientX, y: e.clientY });
    window.addEventListener("mousemove", f);
    return () => {
      window.removeEventListener("mousemove", f);
    };
  }, []);
  return props.children(pos);
}

ReactDOM.render(<Parent />, document.getElementById("root"));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();