Mantine UI - 将 useMantineColorScheme 与 NextJS 一起使用 - ColorSchemeProvider 丢失

Tyl*_*ler 1 reactjs next.js mantine

我有一个 NextJS 应用程序,我想使用 Mantine 作为 UI 库,但是我遇到了设置问题。

我基本上完全遵循了标准设置说明,但是出现以下错误:

Error: useMantineColorScheme hook was called outside of context, make sure your app is wrapped with ColorSchemeProvider component

我希望渲染的组件如下所示(从此处获取)

我的 mantine 提供器是否放置在错误的位置?

我创建了一个正在运行的副本,它以同样的方式失败在这里

我的代码:

_document.tsx

import { createGetInitialProps } from '@mantine/next'
import Document, { Head, Html, Main, NextScript } from 'next/document'

const getInitialProps = createGetInitialProps()

export default class _Document extends Document {
  static getInitialProps = getInitialProps

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

_app.tsx

import type { AppProps } from 'next/app'
import '../styles/vars.css'
import '../styles/global.css'
import './app.css'
import { NextQueryParamProvider } from 'next-query-params'
import { useEffect } from 'react'
import { MantineProvider } from '@mantine/core'

// This file allows us to inject elements that will be common to all pages.
// when we route to something, this will ultimately be passed to this component as "Component"
// And we can then alter things like styling, routing, etc.
function MyApp({ Component, pageProps }: AppProps) {
  
  return (
    <>
      <NextQueryParamProvider>
        <MantineProvider
          withGlobalStyles
          withNormalizeCSS
          theme={{
            /** Put your mantine theme override here */
            colorScheme: 'light',
          }}
        >
          <Component {...pageProps} />
        </MantineProvider>
      </NextQueryParamProvider>
    </>
  )
}

export default MyApp
Run Code Online (Sandbox Code Playgroud)

colorComponent.tsx

import { useMantineColorScheme, ActionIcon, Group } from '@mantine/core';
import { IconSun, IconMoonStars } from '@tabler/icons';

export function ActionToggle() {
  const { colorScheme, toggleColorScheme } = useMantineColorScheme();

  return (
    <Group position="center" my="xl">
      <ActionIcon
        onClick={() => toggleColorScheme()}
        size="lg"
        sx={(theme) => ({
          backgroundColor:
            theme.colorScheme === 'dark' ? theme.colors.dark[6] : theme.colors.gray[0],
          color: theme.colorScheme === 'dark' ? theme.colors.yellow[4] : theme.colors.blue[6],
        })}
      >
        {colorScheme === 'dark' ? <IconSun size={18} /> : <IconMoonStars size={18} />}
      </ActionIcon>
    </Group>
  );
}
Run Code Online (Sandbox Code Playgroud)

Tyl*_*ler 6

事实证明 ColourSchemeProvider 确实与 MantineProvider 是分开的,但我没有意识到这一点。可以通过向文件添加 ColorSchemeProvider 来解决此问题_app.tsx

这里提供了一个示例。

从示例复制:

import { GetServerSidePropsContext } from 'next';
import { useState } from 'react';
import { AppProps } from 'next/app';
import { getCookie, setCookie } from 'cookies-next';
import Head from 'next/head';
import { MantineProvider, ColorScheme, ColorSchemeProvider } from '@mantine/core';
import { NotificationsProvider } from '@mantine/notifications';

export default function App(props: AppProps & { colorScheme: ColorScheme }) {
  const { Component, pageProps } = props;
  const [colorScheme, setColorScheme] = useState<ColorScheme>(props.colorScheme);

  const toggleColorScheme = (value?: ColorScheme) => {
    const nextColorScheme = value || (colorScheme === 'dark' ? 'light' : 'dark');
    setColorScheme(nextColorScheme);
    setCookie('mantine-color-scheme', nextColorScheme, { maxAge: 60 * 60 * 24 * 30 });
  };

  return (
    <>
      <Head>
        <title>Mantine next example</title>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
        <link rel="shortcut icon" href="/favicon.svg" />
      </Head>

      <ColorSchemeProvider colorScheme={colorScheme} toggleColorScheme={toggleColorScheme}>
        <MantineProvider theme={{ colorScheme }} withGlobalStyles withNormalizeCSS>
          <NotificationsProvider>
            <Component {...pageProps} />
          </NotificationsProvider>
        </MantineProvider>
      </ColorSchemeProvider>
    </>
  );
}

App.getInitialProps = ({ ctx }: { ctx: GetServerSidePropsContext }) => ({
  colorScheme: getCookie('mantine-color-scheme', ctx) || 'light',
});
Run Code Online (Sandbox Code Playgroud)