0

I have an app under <div id="app"> and a portal root element <div id="portal"> (https://reactjs.org/docs/portals.html).

ReactDOM.render(<App />, document.getElementById('app'));

I would like to toggle between inline and portal while video is playing.

I hope to avoid video from pausing, or at least user will not detect the pause.

Inline:

<body>
  <div id="app">
    <div>
      <button>Toggle inline/portal</button>
      <div class="inline">
        <video></video>
      </div>
    </div>
  </div>
  <div id="portal">
  </div>
</body>

Portal (css for frame full screen):

<body>
  <div id="app">
    <div>
      <button>Toggle inline/portal</button>
      <div class="inline">
      </div>
    </div>
  </div>
  <div id="portal">
    <video></video>
  </div>
</body>

Is this possible? How can I achieve it in React?

4

2 回答 2

0

您可以有条件地更改 CSS,而不是拥有两个容器:

import { useState } from "react";

const App = () => {
  const [cssStyle, setCssStyle] = useState("inline");

  const toggleVideoMode = () => {
    const mode = cssStyle === "inline" ? "portal" : "inline";
    setCssStyle(mode);
  };

  return (
    <div>
      <button onClick={toggleVideoMode}>Toggle inline/portal</button>
      <div className={cssStyle}>
        <video><video>
      </div>
    </div>
  );
};

export default App;
于 2021-04-28T17:15:32.830 回答
0

这可以通过在 React 中使用状态轻松完成,

import { useState } from "react";
import "./styles.css";

function VideoComponent(props) {
  console.log(props)
  return <p>Hi I am a video, inline mode: {JSON.stringify(props.mode)}</p>;
}

export default function App() {
  const [inlineMode, setInlineMode] = useState(true);

  return (
    <div className="App">
        <div id="app">
        <div>
          <button onClick={()=>setInlineMode(!inlineMode)}>Toggle inline/portal</button>
          <div className="inline">
            {inlineMode && <VideoComponent mode={inlineMode}/>}
          </div>
        </div>
      </div>
      <div id="portal">
      {!inlineMode && <VideoComponent mode={inlineMode}/>}
      </div>
    </div>
  );
}

CodeSandbox 示例

于 2021-04-28T17:17:42.647 回答