打开我们刚刚新建的react 项目 todolist, 下面是它的目录结构。src 下的index.js 是整个项目的入口文件。
可以看到index.js 中引入了serviceWorker 它是一个PWA,离线页面的内容。
我们暂且可以先不用它。删掉那两行。
然后,这个文件引入了index.css 也可以删掉。
然后呢,src 下,有一个文件App.test.js 这个是,我们使用jest 做测试时候的文件,暂时也可以删除。
然后,我们打开App.js ,将它的内容改为,如下。
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div>
hello world
</div>
);
}
}
export default App;
然后呢,项目根目录下的 public/index.html 就是项目的html 文件。这个文件内容是空的,如下。
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
然后呢,在 项目的入口文件 index.js 中。就使用reactdom 将app 组件渲染到 ID 为root 的元素里。
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
最后呢,如何用react 定义一个组件呢。如下图。首先 使用class 声明 然后这个class 要extends Component 。然后,class 里面,必须有render 函数,这个函数返回的是,页面显示的内容。
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>
hello world
</div>
);
}
}
export default App;