그림 속 그림 창에 React 구성 요소 탑재

DDD
풀어 주다: 2024-09-18 22:57:27
원래의
327명이 탐색했습니다.

Mounting a React component in a picture in picture window

Google은 Chrome 116에 documentPictureInPicture API를 도입했습니다.

이 기사에서는 기본 애플리케이션에 먼저 마운트할 필요 없이 PIP 창에 간단한 반응 구성 요소를 마운트하는 방법을 살펴봅니다.

1단계 - 구성요소 구조 설정
우리는 두 가지 구성 요소를 만듭니다. MainComponent.js 및 Counter.js. MainComponent.js에서는 PIP 창에서 Counter.js 구성 요소를 여는 간단한 버튼을 설정합니다.

MainComponent.js

import React from "react";

const MainComponent = () => {
 async function openPictureInPicture() {
  // 
 }

 return (
  <div>
   <div onClick={openPictureInPicture}>Open counter</div>
  </div>
 );
};

export default MainComponent;
로그인 후 복사

Counter.js

import React, { useState, useEffect } from "react";
const Counter = () => {
 const [count, setCount] = useState(0);

 useEffect(() => {
  setCount(1);
 }, []);

 const addNumber = () => {
  setCount((prevCount) => prevCount + 1);
 };
 const subtractNumber = () => {
  setCount((prevCount) => prevCount - 1);
 };

 try {
  return (
   <div>
    <div onClick={subtractNumber}>-</div>
    <button>{count}</button>
    <div onClick={addNumber}>+</div>
   </div>
  );
 } catch (error) {
  console.error("ERROR_CODE: _RENDER\n", error);
  return <></>;
 }
};

export default Counter;
로그인 후 복사

2단계 - PIP 기능 추가
openPictureInPicture() 함수에서 PIP 창을 요청합니다.

const pipWindow = await window.documentPictureInPicture.requestWindow();
로그인 후 복사

pip 창 본문에 div 요소를 만듭니다. 이 div에는 Counter.js를 마운트할 것입니다

const pipDiv = pipWindow.document.createElement("div");
pipDiv.setAttribute("id", "pip-root");
pipWindow.document.body.append(pipDiv);
로그인 후 복사

이제 ID가 "pip-root"인 div에 Counter.js 구성 요소를 마운트합니다.

const PIP_ROOT = ReactDOM.createRoot(
        pipWindow.document.getElementById("pip-root")
);
PIP_ROOT.render(<Counter />);

로그인 후 복사

3단계 — 모든 항목 결합
최종 MainComponent.js 코드는 다음과 같아야 합니다.

import React from "react";
import Counter from "./Counter";
import ReactDOM from "react-dom/client";

const MainComponent = () => {
 async function openPictureInPicture() {
  const pipWindow = await window.documentPictureInPicture.requestWindow();
  const pipDiv = pipWindow.document.createElement("div");
  pipDiv.setAttribute("id", "pip-root");
  pipWindow.document.body.append(pipDiv);
  const PIP_ROOT = ReactDOM.createRoot(pipWindow.document.getElementById("pip-root"));
  PIP_ROOT.render(<Counter />);
 }

 return (
  <div>
   <div onClick={openPictureInPicture}>Open counter</div>
  </div>
 );
};

export default MainComponent;
로그인 후 복사

이제 PIP 창에 자체 반응 구성 요소를 탑재할 수 있습니다!

위 내용은 그림 속 그림 창에 React 구성 요소 탑재의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!