Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

reactjs - Manually setting Desktop vesion in React

I have a custom Hook useWindowSize that determines whether there is a Mobile or Desktop environment. This is fine for most cases except when a mobile user wants to access the desktop version on his/her phone. I have a button to manually override the current windowsize but am not sure how to approach this.

Here I determine the opposite of the loaded windowsize but how can I switch and reload to the appropriate mode on click?

I will need this mode to stay afterwards even if the window is resized to keep the components linked to either mobile or desktop.

import "./styles.css";
import "./app.scss";
import useWindowSize from "./useWindowSize";

export default function App() {
  const windowSize = useWindowSize();
  const otherMode = windowSize <= "useMobileVersion" ? "useDesktopVersion" : "useDesktopVersion";
  return (
    <div className="App">
      <p>Right now you are in {windowSize} mode. <button onClick={() => setPageMode("otherMode")}>
      Switch to {otherMode} mode
      </button>
      </p>
    </div>
  );
}

The codesandbox is here. The custom Hook is her:

import { useState, useEffect } from "react";

//a Util function that will convert the absolute width into breakpoints
function getBreakPoint(windowWidth) {
  if (windowWidth) {
    if (windowWidth < 420) {
      return "useMobileVersion";
    } else {
      return "useDesktopVersion";
    }
  } else {
    return "useDesktopVersion";
  }
}
function useWindowSize() {
  const isWindowClient = typeof window === "object";

  const [windowSize, setWindowSize] = useState(
    isWindowClient ? getBreakPoint(window.innerWidth) : undefined
  );

  useEffect(() => {
    //a handler which will be called on change of the screen resize
    function setSize() {
      setWindowSize(getBreakPoint(window.innerWidth));
    }

    if (isWindowClient) {
      //register the window resize listener
      window.addEventListener("resize", setSize);

      //unregister the listener
      return () => window.removeEventListener("resize", setSize);
    }
  }, [isWindowClient, setWindowSize]);

  return windowSize;
}

export default useWindowSize;
question from:https://stackoverflow.com/questions/65910467/manually-setting-desktop-vesion-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...