Art*_*nko 11 reactjs create-react-app
我开始学习反应,现在我想明白了什么是的目的index.js
和App.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();
Run Code Online (Sandbox Code Playgroud)
我看到了类似的问题反应原生,但我想知道这一般反应.
Har*_*n L 13
index.js
是所有节点应用程序的传统和实际入口点.在这里作出反应,它只具有渲染内容和渲染位置的代码.
App.js
另一方面,具有react应用程序的根组件,因为每个视图和组件都在React中使用层次结构进行处理,其中层次结构中<App />
是最顶层的组件.这使您感觉从代码开始维护代码的层次结构App.js
.
除此之外,您可以将App逻辑放在index.js
文件本身中.但它与使用库或框架的社区遵循的约定有关.和社区一起去感觉总是很好.
Eva*_*son 12
很好的问题。答案是App.js不是必需的,我个人将其删除并仅使用Index.js作为根。
人们“说”它使它看起来更好/更容易,但它只是添加了一个不必要的额外步骤。我希望他们最终将 App.js 从 npx create-react-app 中删除,只使用 index.js。
编辑:我不会改变我原来的评论,但是,我放弃了删除 App.js。我现在只是通过 App.js 汇集所有内容并使用 Index.js。index.js 的好处是您可以在那里进行所有导入并通过 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'));
Run Code Online (Sandbox Code Playgroud)