首页 > 解决方案 > 在 React 中侦听 JavaScript 媒体查询

问题描述

我正在尝试实现在 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;

我究竟做错了什么?

标签: javascriptreactjsmedia-queriesaddeventlistener

解决方案


因此MediaQueryList matches方法返回一个布尔值。

您应该只返回您的MediaQueryList以便以后能够向其添加监听器:

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

推荐阅读