淘先锋技术网

首页 1 2 3 4 5 6 7

魔术.. (The Magic..)

We listed for this event, MediaQueryListEvent and we get an object that looks something like this back.

我们为该事件列出了MediaQueryListEvent并得到了一个看起来像这样的对象。

MediaQueryListEvent : {
isTrusted: true,
media: "(min-width: 768px)",
matches: true,
...
}

We are looking to see if we get a match from the query and if so, then we want to take action.

我们正在寻找是否从查询中获得匹配,如果有,那么我们想采取行动。

Let’s set up our state variable mQuery using useState and initialized it by getting the current window innerWidth.

让我们使用useState设置状态变量mQuery ,并通过获取当前窗口innerWidth对其进行初始化。

const [mQuery, setMQuery] = React.useState<any>({
matches: window.innerWidth > 768 ? true : false,
});

In our component we will listen for this event, from the window object by calling window.matchMedia

在我们的组件中,我们将通过调用window.matchMediawindow对象监听此事件。

useEffect(() => {
let mediaQuery = window.matchMedia("(min-width: 768px)");
mediaQuery.addListener(setMQuery); // this is the cleanup function to remove the listener
return () => mediaQuery.removeListener(setMQuery);
}, []);

the addListener calls our setState function to hold the results, and the changing of the state variable will cause the component to rerender.

addListener调用我们的setState函数来保存结果,状态变量的更改将导致组件重新呈现。

Based on the state variable we will render the hamburger menu or the list of buttons that correspond to the side menu items

根据状态变量,我们将呈现汉堡菜单或与侧面菜单项相对应的按钮列表

NavButtons组件的完整源代码 (Full source for NavButtons component)

// NavButtons.tsx
export const NavButtons = () => {
const [mQuery, setMQuery] = React.useState<any>({
matches: window.innerWidth > 768 ? true : false,
}); useEffect(() => {
let mediaQuery = window.matchMedia("(min-width: 768px)");
mediaQuery.addListener(setMQuery); // this is the cleanup function to remove the listener
return () => mediaQuery.removeListener(setMQuery);
}, []); // MediaQueryListEvent { isTrusted: true, media: "(min-width: 768px)", matches: true ...} return (
<div>
{mQuery && !mQuery.matches ? (
<IonMenuButton />
) : (
<>
<IonButton routerLink={"/home"}>Home </IonButton>
<IonButton routerLink={"/page-1"}>One </IonButton>
<IonButton routerLink={"/page-2"}>Two</IonButton>
</>
)}
</div>
);
};

Then we use the component in the IonToolbar of our pages, see an example below

然后,我们在页面的IonToolbar中使用该组件,请参见下面的示例

// Home.tsx
const Home: React.FC = () => {
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>HOME</IonTitle>
<IonButtons slot="end">
<NavButtons/> // <== OUR COMPONENT
</IonButtons>
</IonToolbar>
</IonHeader>
<IonContent fullscreen>
</IonContent>
</IonPage>
);
};export default Home;

GitHub中项目的完整源代码 (Full Source Code for the Project In GitHub)

https://github.com/aaronksaunders/sidemenu-topnav-ionic-react

https://github.com/aaronksaunders/sidemenu-topnav-ionic-react

翻译自: https://medium.com/swlh/using-window-matchmedia-for-media-queries-in-reactjs-97ddc66fca2e