【问题标题】:Listening for JavaScript Media Queries in React在 React 中侦听 JavaScript 媒体查询
【发布时间】:2021-02-13 08:25:09
【问题描述】:

我正在尝试在 React 中实现 here 的媒体查询概念。如下所示,我得到以下信息:

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;

我做错了什么?

【问题讨论】:

    标签: javascript reactjs media-queries addeventlistener


    【解决方案1】:

    这是因为您将 const isMobile 设置为类型布尔(真/假)而不是上层对象(函数) 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
    

    【讨论】:

      【解决方案2】:

      相应地MediaQueryListmatches方法返回一个布尔值。

      您应该只返回您的 MediaQueryList 以便以后能够addListener 给它:

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

      【讨论】:

        猜你喜欢
        • 2018-01-21
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 2011-10-15
        • 2014-11-09
        • 1970-01-01
        • 1970-01-01
        • 2014-01-11
        相关资源
        最近更新 更多