【问题标题】:React JS (Element type is invalid)React JS(元素类型无效)
【发布时间】:2021-08-05 00:33:35
【问题描述】:

我正在尝试在 index.js 文件中呈现我的 App 函数。但它一直显示此错误: 元素类型无效:应为字符串(用于内置组件)或类/函数(用于复合组件)但得到:对象。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。 检查App的渲染方法。

App.js

import React from "react";
import { Container, AppBar, Typography, Grow, Grid} from '@material-ui/core';
import memories from './images/memories.png';
import Posts from './components/Posts/Posts';
import Form from './components/Form/Form.js';

const App = () => {
    return(
        <Container maxwidth="lg">
            <AppBar position="static" color="inherit">
                <Typography variant="h2" align="center">Memories</Typography>
                <img src={memories}  alt="memories" height="60"/>
            </AppBar>
            <Grow in>
                <Container>
                    <Grid container justify="space-between" alignItems="stretch" spacing={3}>
                        <Grid item xs={12} sm={7}>
                            <Posts/>
                        </Grid>
                        <Grid item xs={12} sm={4}>
                            <Form/>
                        </Grid>

                    </Grid>
                </Container>
            </Grow>
        </Container>
    )
}
export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));

【问题讨论】:

  • memoriesPostsForm 是否都有默认导出?
  • 我已经在我的 Codesandbox 上尝试了你的代码。但如果你导入 Post and Form 组件“codesandbox.io/s/elementtype-gyr48?file=/src/App.js”效果很好,请检查这个
  • 嗨!欢迎来到 StackOverflow。这部分代码很好,错误与代码的其他组件或部分有关。可以在沙盒中在线复现吗?
  • 我猜,错误是由您未在帖子中显示的其他组件引起的
  • 嗨,@USK,你检查了吗?

标签: javascript reactjs components react-component react-dom


【解决方案1】:

我使用了export default function Form(){} 而不是export default Form。问题已解决,我不知道原因。感谢所有回答的人。

【讨论】:

    猜你喜欢
    • 2021-05-21
    • 2019-02-17
    • 2022-12-16
    • 2019-09-01
    • 2019-07-04
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多