代码之家  ›  专栏  ›  技术社区  ›  Deus Ex

进口React组件未显示

  •  0
  • Deus Ex  · 技术社区  · 11 月前

    我导入了一个react组件,但它没有显示在页面上。

    这是我的app.js文件。我导入了“functionalComponent”组件,但它没有显示在浏览器上。

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';
    import functionalComponent from './functionalComponent';
    import classComponent from './classComponent';
    
    function App() {
      return (
        <div className="App">
         
          <functionalComponent/>
        </div>
      );
    }
    
    export default App;
    

    这是我的函数Component.js

    import React from "react";
    
    class functionalComponent extends React.Component{
    
        render(){
            return <p>This is a functional component.</p>
        }
    }
    
    export default functionalComponent;
    

    这是我的App.test.js

    import { render, screen } from '@testing-library/react';
    import App from './App';
    
    test('renders learn react link', () => {
      render(<App />);
      const linkElement = screen.getByText(/learn react/i);
      expect(linkElement).toBeInTheDocument();
    });
    
    2 回复  |  直到 11 月前
        1
  •  1
  •   koushik deb    11 月前

    React要求组件的第一个字母大写 将组件名称更改为FunctionalComponent,并检查这是否解决了问题。

    import React from "react";
    const FunctionalComponent = () => {   
        return <p>Functional component</p>   
    }
    
    export default FunctionalComponent;
    

    谢谢

        2
  •  0
  •   Ahmed Sbai    11 月前
    import React from "react";
    
    const FunctionalComponent = () => {  
      // render() method does not exist we are no longer in a Class context
      return <p>This is a functional component.</p>   
    }
    
    export default FunctionalComponent ;
    

    这就是函数组件的外观,就像您的 App 组件,在您的示例中,您正在使用一个类

        3
  •  0
  •   Ashish Sharma    11 月前

    组件名称应为FunctionalComponent,而不是FunctionalComponent。JavaScript区分大小写,因此不正确的大小写会阻止识别组件。

    import FunctionalComponent from './functionalComponent';
    
     function App() {
      return (
      <div className="App">
      <FunctionalComponent />
     </div>
      );
     }
    
    export default App;
    

    在functionalComponent.js中: 从“React”导入React;

     class FunctionalComponent extends React.Component {
      render() {
     return <p>This is a functional component.</p>;
      }
     }
    
    export default FunctionalComponent;