React组件导入异常求助:组件无法正常渲染问题排查
React组件无法导入渲染的排查与修复
核心问题:组件命名不符合React规范
React规定自定义组件名必须首字母大写,小写开头的标签会被识别为原生HTML元素,所以你写的<teste/>根本不会被当作自定义组件处理。
具体修复操作:
调整组件文件与函数名
- 把
components目录下的teste.js重命名为Teste.js - 修改组件内的函数定义:
import React from 'react' export default function Teste() { return ( <div>teste</div> ) }
- 把
更新App.js中的导入与使用
import Teste from './components/Teste'; import './App.css'; // 记得导入styled-components,否则会报错 import styled from 'styled-components'; function App() { return ( <Container> <Teste /> </Container> ); } const Container = styled.div` display: flex; justify-content: center; align-items: center; height: 100vh; width: 100%; background: blue; ` export default App;
额外排查点
- 确认styled-components依赖已安装:你的代码用到了
styled.div但没导入,也没说明是否安装。执行npm install styled-components完成安装。 - 核对文件夹结构:确保
Teste.js确实在src/components/目录下,如果组件放在子文件夹(比如components/teste/Teste.js),导入路径要对应改成./components/teste/Teste。
内容的提问来源于stack exchange,提问作者Jhonatta
相关产品推荐
相关产品推荐

