为什么 create-react-app 同时创建 App.js 和 index.js?

Why does create-react-app creates both App.js and index.js?

我开始学习 React,现在我正试图了解由 运行 create-react-app 创建的 index.jsApp.js 的目的是什么。

为什么我们不能直接使用,例如。 App.js?

我读到 App.js 通常用作应用程序的主要入口点,但 index.js 的自动生成代码似乎是主要入口点的一部分:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

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

我看到了类似的反应原生问题,但我想了解一般的反应。

create-react-app 使用名为 html-webpack-plugin 的 webpack 插件,此插件使用 index.js 作为入口点,如下所示:

const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
 entry: 'index.js',
 output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
 plugins: [
new HtmlWebpackPlugin()
 ]
}

此插件用于生成 html 文件。

index.js 是所有节点应用程序的传统和实际入口点。在 React 中,它只有渲染内容和渲染位置的代码。

另一方面,

App.js 具有 React 应用程序的根组件,因为在 React 中每个视图和组件都是通过层次结构处理的,其中 <App /> 是层次结构中最顶层的组件。这让您感觉您在代码中维护从 App.js.

开始的层次结构

除此之外,您可以在 index.js 文件本身中包含应用程序逻辑。但它与使用库或框架的社区遵循的约定有关。和社区一起走总是感觉很好。

好问题。答案是 App.js 不需要,我个人删除了它,只使用 Index.js 作为根。

人们“说”它使它看起来更好/更容易,但它只是添加了一个不必要的额外步骤。我希望他们最终会从 npx create-react-app 中删除 App.js 并只使用 index.js.

编辑:我不打算更改我原来的评论,但是,我放弃了删除 App.js。我现在只是通过 App.js 收集所有内容并使用 Index.js。 index.js 的好处是您可以在那里进行所有导入,然后通过 App.js

汇集它们
import React from "react";
import ReactDOM from "react-dom";

function App() {
  return (
    <div className="App">
      <h1>Hello</h1>
      <h2>How are you!</h2>
    </div>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

这是一个示例,我们可以在不使用 App.js 的情况下直接实现。

是的,App.js没有必要。您可以只使用 index.js,如下所示。

// Import React and ReactDOM Libraries.
import React from 'react';
import ReactDOM from 'react-dom';
import CommmentDetail from './CommentDetail';

function getLabelText() {
  return 'Enter Name: ';
}

// Create React Components 
const App = () => {
  const buttonText = {text: 'Submit'};
  const buttonStyle = {backgroundColor: 'blue', color: 'white'}; 
  return (
    <div>
      <label className="label" htmlFor="name">{getLabelText()}</label>  
      <input id="name" type="text" />
      <button style={buttonStyle} >{buttonText.text}</button>

      // You can have other components here as follows.
      // CommmentDetail is someOther component defined in another file.
      // See the import statement for the same, 4th line from top

      <CommmentDetail author='Nivesh' timeAgo='3 months ago at 4.45 PM' commentText='Good Point' } />
    </div>
  )
}

// Take the react component and show it on the screen
// ReactDOM.render(<App />, document.getElementById('root'));
// You can use the following as well.
ReactDOM.render(<App />, document.querySelector('#root'));