简体   繁体   English

我如何在同一个文件中同时使用 class 和功能组件

[英]how can i use both class and functional component in same file

I want to use both class and function in the same file and I am getting a parsing error that我想在同一个文件中同时使用 class 和 function 并且我收到一个解析错误

App is already declared应用程序已声明

My code:我的代码:

import React from 'react'
import './App.css';


class App extends React.Component{
}



function App() {
  return (
    <div>
      
    </div>
  );
}

export default App;

How can I use both class and functional component in same file?如何在同一个文件中同时使用 class 和功能组件?

You cannot use a class component with a functional component inside of it.您不能使用内部带有功能组件的 class 组件。 Because they work different, for example.例如,因为它们的工作方式不同。 Inside a class based component you have the render method that returns an html.在基于 class 的组件中,您具有返回 html 的render方法。

import React, { Component } from "react";

class ClassComponent extends Component {
 render() {
   return <h1>Hello, world</h1>;
 }
} 

And in a functional component the return of the function is and html.在一个功能组件中,function 的返回是和 html。

import React from "react";

function FunctionalComponent() {
 return <h1>Hello, world</h1>;
}

You can also declare a functional component through a anonymous function也可以通过匿名 function 声明一个功能组件

import React from "react";
 
const FunctionalComponent = () => {
 return <h1>Hello, world</h1>;
};

For further information you can check here or the documentation有关更多信息,您可以查看 此处文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应:如何访问 class 组件中的功能组件的道具 - React: How can I acces to props of a functional component in a class component 我怎样才能把这个 React class 组件变成一个功能组件? - How can i turn this React class component into a functional component? 我如何编写此类组件来响应功能组件。? - How can i write this class component to react functional component.? 我应该使用哪个组件 class 或功能? - Which component should I use class or functional? 如何在功能组件中使用 {...this.props} - How can I use {...this.props} in a functional component 如何从 sass 文件访问功能组件中的 className - How can i access the className in a functional component from sass file React 16.7具有状态挂钩,在任何情况下都可以使用功能组件而不是类组件吗? - React 16.7 has State Hook, can I use functional component instead of class component in any situation? 如何编写返回 class 组件作为功能组件的 React 组件? - How can I write React component that returns a class component as a functional component? 我可以将 class 组件更改为功能组件吗? - Reactjs - Can I change class component into functional component? - Reactjs ReactJS - 如何将 Class 组件与组合 state 更新到功能组件的副作用 - ReactJS - How can I transform a Class Component withsSide-effects of combined state updates to a Functional Component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM