简体   繁体   English

React TypeScript如何将事件侦听器附加到window.matchMedia

[英]React TypeScript How to attach an event listener to window.matchMedia

When the react page loads it detects if the user has set dark mode in their operating system 加载反应页面时,它会检测用户是否在操作系统中设置了暗模式

const darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;

and then renders one of two images depending on the result 然后根据结果渲染两个图像之一

import logoDark from '../images/logoDark.svg';
import logoLight from '../images/logoLight.svg';

<img src={darkMode ? logoDark : logoLight} />

But if the user changes mode after the page has loaded the image isn't updated, how do I add an event listener to window.matchMedia ? 但是,如果用户在页面加载图像后更改模式未更新,如何将事件侦听器添加到window.matchMedia?

I have tried with.. 我试过了..

  darkMode.addEventListener( "change", (e) => {
    darkMode = e.matches;
    console.log(e.matches) // true / false
  });

but I get the error Type 'boolean' is not assignable to type 'MediaQueryList'.ts(2322) 但出现错误Type 'boolean' is not assignable to type 'MediaQueryList'.ts(2322)

UDATE : Working Code UDATE :工作代码

import React, {useContext} from "react";
import Context from '../components/context';
import logoDark from '../images/logoDark.svg';
import logoLight from '../images/logoLight.svg';

const Home: React.FC = () => {
  const darkMode = window.matchMedia('(prefers-color-scheme: dark)');   
  darkMode.addEventListener( "change", (e) => {
    if (e.matches) {
      setGlobal({...global, mode: true})
    } else {
      setGlobal({...global, mode: false})
    }
  });
  return (
  <img src={global.mode ? logoDark : logoLight} />
}

export default Home;

darkMode is a state that has type value if I understand correctly. 如果我正确理解, darkMode是具有type值的状态。 And if it is not it should be in state in order to manipulate it. 如果不是,它应该处于状态以便操纵它。 The type e.matches returns is a Boolean as you see. 如您所见,类型e.matches返回为布尔值。 So, you need to change the darkMode type to Boolean.. 因此,您需要将darkMode类型更改为Boolean。

And setState, base on the condition. 和setState,基于条件。 I do not have the complete code so, I will not make guesses. 我没有完整的代码,所以我不会猜测。 If you paste more code samples I can help more.. 如果您粘贴更多代码示例,我可以提供更多帮助。

You are adding eventListener on matches, which is boolean. 您要在匹配项上添加eventListener,它是布尔值。 You have to do it like below code: 您必须像下面的代码那样做:

 var darkMode = window.matchMedia('(prefers-color-scheme: dark)'); darkMode.addEventListener( "change", (e) => { if (e.matches) { //Perform your action for dark } else { //Perform other action } }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM