You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件显示异常及no-unused-vars报错问题求助

问题描述

尝试创建一个包含文本的React组件,将text.js文件导入到app.js的App组件中渲染,但页面仅显示“hello”,且出现ESLint警告:'text' is defined but never used。

现有代码

app.js

import './App.css';
import text from './text';

function App() {
  return (
    <div className="App">
      <p>hello</p>
      <text></text>
    </div>
  );
}

export default App;

text.js

import React from 'react'
export default function text() {
  return (
    <div>
      <h1>Hey</h1>
    </div>
  );
}

报错信息

[eslint]
src\App.js
  Line 3:8:  'text' is defined but never used  no-unused-vars 

Search for the keywords to learn more about each warning.     
To ignore, add // eslint-disable-next-line to the line before.

WARNING in [eslint]
src\App.js
  Line 3:8:  'text' is defined but never used  no-unused-vars 

webpack compiled with 1 warning
解决方法

问题核心是React组件命名必须以大写字母开头——这是React的强制规则:小写开头的标签会被识别为原生HTML标签(而非自定义组件),因此你写的<text></text>并没有调用导入的组件,反而被当成了不存在的原生标签,导致内容不渲染,同时ESLint判定导入的text变量未被使用。

只需做两处修改:

  1. 修改text.js中的组件名称为大写开头:
import React from 'react'
// 组件名改为大写Text
export default function Text() {
  return (
    <div>
      <h1>Hey</h1>
    </div>
  );
}
  1. 修改app.js中的导入语句和组件调用,统一使用大写名称:
import './App.css';
// 导入时使用大写Text
import Text from './text';

function App() {
  return (
    <div className="App">
      <p>hello</p>
      // 调用大写的Text组件
      <Text></Text>
    </div>
  );
}

export default App;

修改完成后重新编译,页面会同时显示“hello”和“Hey”,ESLint的警告也会消失。

内容的提问来源于stack exchange,提问作者Lakshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 13:05:15