美文网首页
useRef 当 this 使用

useRef 当 this 使用

作者: 想溜了的蜗牛 | 来源:发表于2021-12-06 09:42 被阅读0次

有类似实例变量的东西吗?

以下为一个示例,操作window 窗口打开和关闭

import React, { useState, useRef } from "react";
import "./styles.css";
export default function App() {
  let [isOpen, setIsOpen] = useState(false);
  const openWindowRef = useRef();
  const openWindow = () => {
    const iWindow = openWindowRef.current;
    if (iWindow && !iWindow.closed) {
      // iWindow.location.reload();
      iWindow.focus();
    } else {
      openWindowRef.current = window.open(
        "https://google.com",
        "imtools",
        "location=no,top=0,left=100,width=1125,height=700"
      );
    }
    console.log("... imWindow", openWindowRef);
  };
  const closeIMwindow = () => {
    const iWindow = openWindowRef.current;
    iWindow && iWindow.close();
  };
  return (
    <div className="App">
      <button
        onClick={() => {
          setIsOpen(!isOpen);
          if (isOpen) {
            openWindow();
          } else {
            closeIMwindow();
          }
        }}
      >
        {isOpen ? "打开" : "关闭"}
      </button>
      <h1>useRef 当 this 使用</h1>
      <h2>useRef的current可以当成一个this或者新建的对象来使用,</h2>
    </div>
  );
}

在线示例 react-hooks-useref-4-this

相关文章

网友评论

      本文标题:useRef 当 this 使用

      本文链接:https://www.haomeiwen.com/subject/znzsxrtx.html