在 React 中监听 JavaScript 媒体查询

Listening for JavaScript Media Queries in React

我正在尝试实现 here 在 React 中发现的媒体查询概念。通过下面显示的内容,我得到以下信息:

TypeError: isMobile.addListener is not a function
function App() {
    // Saving current page to state 
    let location = useLocation();

    useEffect(() => {
        useStore.setState({ currentPage: location })
    }, [location]);

    // Check if viewing in landscape on mobile
    const isMobile = window.matchMedia("only screen and (max-width: 830px)").matches;

    const setOrientation = (e) => {
        if (e.isMobile) {
            if (window.innerHeight > window.innerWidth){
                // is not landscape
            } else{
                // is landscape
            }
        }
    }

    useEffect(() => {
        setOrientation(isMobile)
        isMobile.addListener(setOrientation)

        return () => isMobile.removeEventListener(setOrientation)
    }, []);

    return (
        <div className="App"></div>
    );
}

export default App;

我做错了什么?

因此 MediaQueryList matches 方法 return 是一个布尔值。

您应该只 return 您的 MediaQueryList 以便稍后能够 addListener 它:

const isMobile = window.matchMedia("only screen and (max-width: 830px)")

这是因为您将 const isMobile 设置为类型 Boolean (true/false) 而不是上层对象 (function) window.matchMedia('string_query')

尝试这样的事情:

const isMobile = window.matchMedia("only screen and (max-width: 830px)")

typeof isMobile
"object"

isMobile.matches
true

function handleTabletChange(e) {
  // Check if the media query is true
  if (e.matches) {
    // Then log the following message to the console
    console.log('Media Query Matched!')
  }
}

isMobile.addListener(handleTabletChange)

您的代码在做什么:

const isMobile = window.matchMedia("only screen and (max-width: 830px)").matches

typeof isMobile
"boolean"

isMobile.matches
undefined

function handleTabletChange(e) {
  // Check if the media query is true
  if (e.matches) {
    // Then log the following message to the console
    console.log('Media Query Matched!')
  }
}

isMobile.addListner(handleTabletChange)

Uncaught TypeError: isMobile.addListner is not a function