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

时间:2018-05-23 16:15:43

标签: reactjs create-react-app

我开始学习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();

我看到了一个类似的问题反应原生,但我想知道这一般的反应。

5 个答案:

答案 0 :(得分:9)

index.js是所有节点应用的传统和实际入口点。在这里作出反应,它只具有渲染内容和渲染位置的代码。

另一方面,

App.js具有react应用程序的根组件,因为每个视图和组件都在React中使用层次结构进行处理,其中<App />是层次结构中最重要的组件。这使您感觉从App.js开始在代码中维护层次结构。

除此之外,您可以在index.js文件中拥有App逻辑。但它与使用库或框架的社区所遵循的约定有关。和社区一起去感觉总是很好。

答案 1 :(得分:3)

好问题。答案是 App.js 不是必须的,我个人把它删除了,只用 Index.js 作为根。

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

App.js 不是必需的,尽管人们经常使用它,但您可以并且可能应该删除它并通过 index.js 简化所有内容。

答案 2 :(得分:0)

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 的情况下直接实现。

答案 3 :(得分:0)

是的,不需要 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.

      <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'));

答案 4 :(得分:-1)

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文件。