以下为一个示例,操作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>
);
}
网友评论