簡體   English   中英

使用 Gatsby wrapRootElement TypeScript 時獲取“對象作為 React 子項無效”

[英]Getting "Objects are not valid as a React child" when using Gatsby wrapRootElement TypeScript

我正在嘗試使用 wrapRootElement 瀏覽器 API 在 Gatsby 中實現主題提供程序。 我一直在網上查看示例,但找不到我出錯的地方。 我收到一個錯誤“對象作為 React 子級無效(找到:object 和鍵 {children})。”

這是我第一次使用 Gatsby 瀏覽器 API,我知道問題出在我試圖傳下去的孩子身上,元素是 object,但是看看我可以在網上找到的所有示例,它們都實現了同樣的方法。

蓋茨比瀏覽器.js

import React from "react"

import ThemeWrapper from './src/components/theme/theme'

export function wrapRootElement({ element }) {
    return <ThemeWrapper>{element}</ThemeWrapper>
}

主題.tsx

import * as React from "react"
import { ThemeProvider } from "@material-ui/styles"
import { CssBaseline } from "@material-ui/core"

import ThemeContext from "./themecontext"
import { defaultTheme, darkTheme } from "./themedefinition"

const ThemeWrapper = (children: React.ReactNode) => {

  const [isDarkTheme, setDarkTheme] = React.useState(false);

  const toggleDark = () => {
    setDarkTheme(!isDarkTheme);
  }

  React.useEffect(() => {
    if (window.matchMedia("(prefers-color-scheme: dark)").matches === true) {
      setDarkTheme(true);
    }
  }, [])

  return (
    <ThemeContext.Provider value={{isDarkTheme, toggleDark}}>
      <ThemeProvider theme={isDarkTheme ? darkTheme : defaultTheme}>
        <CssBaseline />
        {children}
      </ThemeProvider>
    </ThemeContext.Provider>
  )
}

export default ThemeWrapper

看起來像一個簡單的錯字:你沒有從你的道具中解構children ,你正在命名第一個參數(道具) children

- const ThemeWrapper = (children: React.ReactNode) => {
+ const ThemeWrapper = ({ children: React.ReactNode }) => {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM