官术网_书友最值得收藏!

Creating our first component

To create our first component, follow these steps:

  1. Open up the newly-created project in your favorite text editor, and run the start command in that project as well to bring up the browser window to see the results of any changes we make along the way.
  2. Let's do something all developers love to do: delete old code!
  3. Once in the code, we can work through the main primary ways to work with React in the latest JavaScript syntax changes that are included in Babel. Given that, let's take a look at the ways to work with React classes. We can either use functions, or we can use classes to introduce React code to our code base. We'll start off with just using functions and over time incorporate classes as well, and we'll discuss how, when, and why to choose each along the way. Granted, either creation method requires React regardless of the implementation method, so we need to actually import it at the start of our code.

  1. At the very top of the App.js file, we're going to add our import statement:
import React from 'react';

This line tells JavaScript that we want to import the React library, and that we can find the React class from the react npm library (Create React App obviously already included that for us). This gives our code the React support that we need, plus it adds support for JSX templates, and everything else we need to be able to write base-level JavaScript !

  1. With our imports out of the way, let's write up our first bit of code:
const App = () => {
return <div className="App">Homepage!</div>;
};

Here, we're diving a little further into some new JavaScript syntax that you may not be used to if you're coming from the older JavaScript world. The previous line is responsible for creating something called a constant function, which limits our ability to redefine or modify the App function after the fact. This function that we're writing doesn't take any arguments and always returns the same thing. This is a functional component, so we need to write the return statement to return out a JSX template that tells React how to render our React component to the browser. We also make sure to tell React that our main component should have a CSS class name called App.

The className, not class! Class is a reserved keyword in JavaScript , so that's why React needs this one little gotcha!
  1. At the end of this code, we'll need to add an export statement to enable other files (such as our index.js file, specifically) to be able to import the right modules into our code base:
export default App;

Our end result is that when our browser refreshes, we should see Homepage! pop up on the screen!

主站蜘蛛池模板: 青铜峡市| 南皮县| 普宁市| 贡嘎县| 铁力市| 河津市| 依安县| 乌拉特前旗| 磐安县| 青州市| 白玉县| 毕节市| 东海县| 云和县| 满城县| 保靖县| 锦州市| 徐汇区| 柏乡县| 余干县| 会理县| 仪陇县| 乌海市| 宁津县| 徐闻县| 高阳县| 锡林浩特市| 射阳县| 海林市| 宣武区| 江川县| 钦州市| 油尖旺区| 河北省| 武威市| 吉木乃县| 板桥市| 凤山县| 桦甸市| 周口市| 孝昌县|