【问题标题】:Can't import react component into a gatsby starter component无法将反应组件导入 gatsby 启动组件
【发布时间】:2023-03-25 14:03:01
【问题描述】:

Gatsby 和 React 的新手。我正在尝试将此响应式导航栏React component 导入this Gatsby starter

我创建了一个 MenuBar,而不是启动器中的 Menu 组件,我从另一个名为 Layout 的组件中调用它。

上面的代码可以工作(从启动器稍微修改),不使用外部组件。

import React from 'react'
import { Link } from 'gatsby'
import styled from '@emotion/styled'
import { useSiteMetadata } from '../hooks/use-site-metadata'

const Header = styled.header`
  background: ${props => props.theme.colors.primary};
  width: 100%;
  padding: 1.5em 0;
`
const Nav = styled.nav`
  width: 100%;
  max-width: ${props => props.theme.sizes.maxWidth};
  margin: 0 auto;
  padding: 0 1.5em;

  ul {
    display: flex;
    justify-content: space-between;
  }

  li {
    display: inline-block;
    margin-left: 1em;
    h2 {
      font-size: 1.2em;
      @media (max-width: ${props => props.theme.responsive.small}) {
        font-size: 1em;
      }
    }
    &:first-of-type {
      position: relative;
      margin: 0;
      flex-basis: 100%;
      h2 {
        font-size: 1.5em;
        @media (max-width: ${props => props.theme.responsive.small}) {
          font-size: 1em;
        }
      }
    }
  }

  a {
    text-decoration: none;
    color: white;
    transition: all 0.2s;
    border-bottom: 2px solid ${props => props.theme.colors.text};
    &:hover {
      color: #e8e6e6;
    }
  }
`

const activeLinkStyle = {
  color: 'white',
}

const Menu = () => {
  const { menuLinks } = useSiteMetadata()
  return (
    <Header>
      <Nav>
        <ul>
          {menuLinks.map(link => (
            <li key={link.name}>
              <Link to={link.slug} activeStyle={activeLinkStyle}>
                <h2>{link.name}</h2>
              </Link>
            </li>
          ))}
        </ul>
      </Nav>
    </Header>
  )
}

export default Menu

但是下面的这个(我导入“响应式动画导航栏”不起作用)。我认为这与渲染方法有关。也许我的问题更多是关于 Javascript 的?欢迎任何有关使其正常工作的帮助。谢谢!

import React from 'react'
import { Link } from 'gatsby'
import styled from '@emotion/styled'
import { useSiteMetadata } from '../hooks/use-site-metadata'
import ReactNavbar from 'react-responsive-animate-navbar'

class MenuBar extends React.Component {
  render() {
    return (
      <ReactNavbar
        color="rgb(25, 25, 25)"
        logo="https://svgshare.com/i/KHh.svg"
        menu={[
          { name: 'HOME', to: '/' },
          { name: 'ARTICLES', to: '/articles' },
          { name: 'ABOUT ME', to: '/about' },
          { name: 'CONTACT', to: '/contact' },
        ]}
        social={[
          {
            name: 'Linkedin',
            url: 'https://www.linkedin.com/in/nazeh-taha/',
            icon: ['fab', 'linkedin-in'],
          },
          {
            name: 'Facebook',
            url: 'https://www.facebook.com/nazeh200/',
            icon: ['fab', 'facebook-f'],
          },
          {
            name: 'Instagram',
            url: 'https://www.instagram.com/nazeh_taha/',
            icon: ['fab', 'instagram'],
          },
          {
            name: 'Twitter',
            url: 'http://nazehtaha.herokuapp.com/',
            icon: ['fab', 'twitter'],
          },
        ]}
      />
    )
  }
}

export default MenuBar 

我收到此错误:

错误:元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

Check the render method of `MenuBar`.
▶ 21 stack frames were collapsed.
(anonymous function)
/home/neto/Documents/gatsbyto/elindustrial/.cache/app.js:165
  162 |   dismissLoadingIndicator()
  163 | }
  164 | 
> 165 | renderer(<Root />, rootElement, () => {
  166 |   apiRunner(`onInitialClientRender`)
  167 | 
  168 |   // Render query on demand overlay

编辑: 谢谢费兰!实际上,我从一开始就在两个文件的顶部都包含了来自“react”的 React,但它们没有出现在我的问题中,因为我弄乱了格式:)。我阅读了有关命名导出与默认导出的信息。我尝试将它作为一个类保留,并且也更改为功能组件,但在这两种情况下我都得到完全相同的错误。

我也尝试过从 Layout 导入:

import MenuBar from '../components/MenuBar'

import {MenuBar} from '../components/MenuBar'

但我一直惨败,上面完全相同的错误。我按照Gatsby guide安装了组件,不知道自己做错了什么。

编辑 2: 按照 Ferran 的建议,将 ReactNavBar 包装在一个空标签中。而且我正在阅读有关功能组件的信息,但仍然没有运气:-S。代码如下:

import React from 'react'
import ReactNavbar from 'react-responsive-animate-navbar'

const MenuBar = props => {
  return (
    <>
      <ReactNavbar
        color="rgb(25, 25, 25)"
        logo="https://svgshare.com/i/KHh.svg"
        menu={[
          { name: 'HOME', to: '/' },
          { name: 'ARTICLES', to: '/articles' },
          { name: 'ABOUT ME', to: '/about' },
          { name: 'CONTACT', to: '/contact' },
        ]}
        social={[
          {
            name: 'Linkedin',
            url: 'https://www.linkedin.com/in/nazeh-taha/',
            icon: ['fab', 'linkedin-in'],
          },
          {
            name: 'Facebook',
            url: 'https://www.facebook.com/nazeh200/',
            icon: ['fab', 'facebook-f'],
          },
          {
            name: 'Instagram',
            url: 'https://www.instagram.com/nazeh_taha/',
            icon: ['fab', 'instagram'],
          },
          {
            name: 'Twitter',
            url: 'http://nazehtaha.herokuapp.com/',
            icon: ['fab', 'twitter'],
          },
        ]}
      />
    </>
  )
}

export default MenuBar

编辑 3 包括布局代码。 我跑了 gastby clean 但仍然遇到同样的错误。我在构建时注意到一个警告,这是警告:

warn "export 'default' (imported as 'ReactNavbar') was not found in
'react-responsive-animate-navbar'
import React, { useEffect } from 'react'
import styled from '@emotion/styled'
import { Global } from '@emotion/core'
// import Menu from '../components/Menu'
import MenuBar from '../components/MenuBar'
import Footer from '../components/Footer'
import { globalStyles } from '../styles/globalStyles.js'

const Root = styled.div``

const Skip = styled.a`
  padding: 0 1rem;
  line-height: 60px;
  background: #2867cf;
  color: white;
  z-index: 101;
  position: fixed;
  top: -100%;
  &:hover {
    text-decoration: underline;
  }
  &:focus,
  &:active,
  &:hover {
    top: 0;
  }
`

const Layout = props => {
  function handleFirstTab(e) {
    if (e.keyCode === 9) {
      document.body.classList.add('user-is-tabbing')
    }
  }
  useEffect(() => window.addEventListener('keydown', handleFirstTab), [])

  return (
    <Root className="siteRoot">
      <div className="siteContent">
        <Skip href="#main" id="skip-navigation">
          Skip to content
        </Skip>
        <MenuBar />
        <div id="main">{props.children}</div>
      </div>
      <Footer />
      <Global styles={globalStyles} />
    </Root>
  )
}

export default Layout

【问题讨论】:

    标签: javascript reactjs jsx gatsby


    【解决方案1】:

    错误:元素类型无效:应为字符串(对于内置 组件)或类/函数(用于复合组件),但得到: 未定义。

    在 99% 的情况下,此问题与导入/导出方法有关,如果某些组件默认导出但以命名方式导入(反之亦然),则会导致提示问题。

    在您的情况下,您将返回一个基于类的组件,但您的问题并非来自于此。您缺少 ReactComponent 的导入,因为您正在扩展它。按照依赖示例:

    import { Link } from 'gatsby'
    import styled from '@emotion/styled'
    import { useSiteMetadata } from '../hooks/use-site-metadata'
    import { ReactNavbar } from "react-responsive-animate-navbar";
    import React, { Component } from 'react';
    
    class MenuBar extends React.Component {
      render() {
        return (
          <ReactNavbar
            color="rgb(25, 25, 25)"
            logo="https://svgshare.com/i/KHh.svg"
            menu={[
              { name: 'HOME', to: '/' },
              { name: 'ARTICLES', to: '/articles' },
              { name: 'ABOUT ME', to: '/about' },
              { name: 'CONTACT', to: '/contact' },
            ]}
            social={[
              {
                name: 'Linkedin',
                url: 'https://www.linkedin.com/in/nazeh-taha/',
                icon: ['fab', 'linkedin-in'],
              },
              {
                name: 'Facebook',
                url: 'https://www.facebook.com/nazeh200/',
                icon: ['fab', 'facebook-f'],
              },
              {
                name: 'Instagram',
                url: 'https://www.instagram.com/nazeh_taha/',
                icon: ['fab', 'instagram'],
              },
              {
                name: 'Twitter',
                url: 'http://nazehtaha.herokuapp.com/',
                icon: ['fab', 'twitter'],
              },
            ]}
          />
        )
      }
    }
    
    export default MenuBar
    

    使用功能组件:

    import React from 'react';
    import { ReactNavbar } from "react-responsive-animate-navbar";
    
    
    const MenuBar = (props) => {
      return <>
        <ReactNavbar
          color="rgb(25, 25, 25)"
          logo="https://svgshare.com/i/KHh.svg"
          menu={[
            { name: `HOME`, to: `/` },
            { name: `ARTICLES`, to: `/articles` },
            { name: `ABOUT ME`, to: `/about` },
            { name: `CONTACT`, to: `/contact` }
          ]}
          social={[
            {
              name: `Linkedin`,
              url: `https://www.linkedin.com/in/nazeh-taha/`,
              icon: [`fab`, `linkedin-in`]
            },
            {
              name: `Facebook`,
              url: `https://www.facebook.com/nazeh200/`,
              icon: [`fab`, `facebook-f`]
            },
            {
              name: `Instagram`,
              url: `https://www.instagram.com/nazeh_taha/`,
              icon: [`fab`, `instagram`]
            },
            {
              name: `Twitter`,
              url: `http://nazehtaha.herokuapp.com/`,
              icon: [`fab`, `twitter`]
            }
          ]}
        />
      </>
    };
    
    export default MenuBar;
    

    解决方案

    深入到库中,该模块似乎没有按照文档的建议默认导出(如在source 中所见),因此需要将其导入为:

    import { ReactNavbar } from "react-responsive-animate-navbar";
    

    【讨论】:

    • 感谢费兰抽出宝贵时间!我搞砸了格式,React 导入从一开始就在那里。尝试了类和功能组件,但不断收到相同的错误。想知道我现在搞砸了什么。
    • 谢谢!试过了,但不幸的是它没有用。将阅读有关功能组件的更多信息。我的印象是,如果我只使用没有 gatsby 的 React,这应该可以工作。
    • 是一样的。在 React 中工作的一切都在 Gatsby 中工作,将两者分开是没有意义的。在试用期间通过gatsby clean 清理缓存。还要检查您要导入 MenuBar 的页面,可能那里有问题
    • 我找到了。需要导入为:import { ReactNavbar } from "react-responsive-animate-navbar";答案已更新
    • 就是这样!你是最棒的,Ferran,谢谢!!
    【解决方案2】:

    这里,MenuBar 是一个类组件

    因此,您不能在其中导入挂钩。

    尝试从 MenuBar 组件中删除以下行

    import { useSiteMetadata } from '../hooks/use-site-metadata'
    

    【讨论】:

    • 谢谢帕尼。不幸的是,这没有用。我只留下了 React 和 ReactNavBar 的导入,得到了同样的错误。
    猜你喜欢
    • 2021-08-21
    • 1970-01-01
    • 2018-10-13
    • 2019-02-27
    • 2021-09-14
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多