- React Cookbook
- Carlos Santana Roldan
- 355字
- 2021-07-16 17:49:34
How to do it...
Let's build our first React application by following these steps:
- Create our React application with the following command:
create-react-app my-first-react-app
- Go to the new application with cd my-first-react-app and start it with npm start.
- The application should now be running at http://localhost:3000.
- Create a new file called Home.js inside your src folder:
import React, { Component } from 'react';
class Home extends Component {
render() {
return <h1>I'm Home Component</h1>;
}
}
export default Home;
File: src/Home.js
- You may have noticed that we are exporting our class component at the end of the file, but it's fine to export it directly on the class declaration, like this:
import React, { Component } from 'react';
export default class Home extends Component {
render() {
return <h1>I'm Home Component</h1>;
}
}
File: src/Home.js
I prefer to export it at the end of the file, but some people like to do it in this way, so it depends on your preferences.
- Now that we have created the first component, we need to render it. So we need to open the App.js file, import the Home component, and then add it to the render method of the App component. If we are opening this file for the first time, we will probably see a code like this:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code>
and save to reload.
</p>
</div>
);
}
}
export default App;
File: src/App.js
- Let's change this code a little bit. As I said before, we need to import our Home component and then add it to the JSX. We also need to replace the <p> element with our component, like this:
import React, { Component } from 'react';
import logo from './logo.svg';
// We import our Home component here...
import Home from './Home';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
{/* Here we add our Home component to be render it */}
<Home />
</div>
);
}
}
export default App;
File: src/App.js
推薦閱讀
- 通信網絡基礎與設備
- 物聯網工程規劃技術
- Force.com Development Blueprints
- WordPress 5 Complete
- NB-IoT物聯網技術解析與案例詳解
- WordPress Web Application Development
- Bonita Open Solution 5.x Essentials
- Master Apache JMeter:From Load Testing to DevOps
- 互聯網+思維與創新:通往未來的+號
- 網絡利他行為研究:積極心理學的視角
- 5G時代的大數據技術架構和關鍵技術詳解
- NB-IoT原理和優化
- 網絡基本通信約束下的系統性能極限分析與設計
- ElasticSearch Server
- 企業網絡組建與維護項目式教程