根据屏幕尺寸渲染组件或渲染嵌入的视频src

时间:2020-03-10 14:13:28

标签: css reactjs

我有此代码块,我想根据屏幕大小渲染BackgroundImage组件或youtube视频src

const HomePage = () => (
  <div>
    <BackgroundImageDiv />
  </div>
);
export default HomePage;

2 个答案:

答案 0 :(得分:2)

我会使用useWindowSize之类的钩子,然后根据该钩子有条件地进行渲染-

function useWindowSize() {
  const isClient = typeof window === 'object';

  function getSize() {
    return {
      width: isClient ? window.innerWidth : undefined,
      height: isClient ? window.innerHeight : undefined
    };
  }

  const [windowSize, setWindowSize] = useState(getSize);

  useEffect(() => {
    if (!isClient) {
      return false;
    }

    function handleResize() {
      setWindowSize(getSize());
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []); // Empty array ensures that effect is only run on mount and unmount

  return windowSize;
}
const HomePage = () => {
  const size = useWindowSize();

  return (
    <div>
      {size.width > 1000 ? <BackgroundImageDiv /> : <YouTube />}
    </div>
  );
}

export default HomePage;

答案 1 :(得分:0)

因此,您想要做的就是继续使用window对象检查屏幕的宽度,并将宽度的值保存在状态变量中,然后您可以选择希望组件在以下时间改变的屏幕尺寸它大于或小于该屏幕尺寸,并使用状态变量width检查并根据该条件有条件地进行渲染

import React, { useState, useEffect,Fragment } from "react";

    const HomePage = () => {
      const [width, setWidth] = useState(window.innerWidth);
      const screenSize = width <= 500;
      useEffect(() => {
        window.addEventListener("resize", () => handleWindowSizeChange());
      }, []);

      const handleWindowSizeChange = () => {

          setWidth(window.innerWidth);

      };

      if (screenSize) {
        return <BackgroundImageDiv />;
      } else {
        return <Fragment>
        <a href="https://www.youtube.com/">Youtube Link</a> 
     </Fragment>;
      }
    };

    export default HomePage;