上QQ阅读APP看书,第一时间看更新
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