发布于 2026-01-06 4 阅读
0

如何使用 Hooks 构建 React 视频模态框

如何使用 Hooks 构建 React 视频模态框

我想与其他前端开发人员分享如何从头开始构建 React 视频模态框。

希望这篇简短的教程对大家都有帮助。

教程末尾我会提供可运行的模态框及其代码的网址,方便您进行测试并查看代码。

首先,我们需要使用 useState Hook 来改变模态框的状态,当用户点击模态框按钮并点击关闭模态框按钮时,模态框的状态就会改变。

其次,当模态框打开并等待从 YouTube 获取视频时,我们将采用相同的方法来构建加载图标,如下所示。

const [modal, setModal] = useState(false);
  const [videoLoading, setVideoLoading] = useState(true);

  const openModal = () => {
    setModal(!modal);
  };

  const spinner = () => {
    setVideoLoading(!videoLoading);
  };
Enter fullscreen mode Exit fullscreen mode

第三,我们将开始编写 JSX 代码部分,为按钮设置 onClick 事件,并使用三元运算符来控制模态框和加载图标,如下所示。

return (
    <div className="App">
      <button onClick={openModal} className="">
        Click Me!
        {modal ? (
          <section className="modal__bg">
            <div className="modal__align">
              <div className="modal__content" modal={modal}>
                <IoCloseOutline
                  className="modal__close"
                  arial-label="Close modal"
                  onClick={setModal}
                />
                <div className="modal__video-align">
                  {videoLoading ? (
                    <div className="modal__spinner">
                      <BiLoaderAlt
                        className="modal__spinner-style"
                        fadeIn="none"
                      />
                    </div>
                  ) : null}
                  <iframe
                    className="modal__video-style"
                    onLoad={spinner}
                    loading="lazy"
                    width="800"
                    height="500"
                    src="https://www.youtube.com/embed/4UZrsTqkcW4"
                    title="YouTube video player"
                    frameBorder="0"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowfullscreen
                  ></iframe>
                </div>
              </div>
            </div>
          </section>
        ) : null}
      </button>
    </div>
  );
Enter fullscreen mode Exit fullscreen mode

这里我留下代码的网址,如果您也想查看 CSS 样式和在线演示,可以点击这里。

代码:https://codesandbox.io/s/nkwxb?file
=/src/App.js:423-1898 在线演示: https: //nkwxb.csb.app/

我希望能够帮助任何想要从零开始构建 React 模态视频而不使用任何库的人。

欢迎在 GitHub 上关注我,并在 LinkedIn 上与我联系。

https://github.com/cesareuseche
https://www.linkedin.com/in/cesar-useche-profile/

文章来源:https://dev.to/cesareuseche/how-to-build-a-react-video-modal-with-hooks-4on4