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

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!

主站蜘蛛池模板: 嘉禾县| 土默特左旗| 绥宁县| 阿坝| 繁峙县| 永兴县| 苗栗县| 清远市| 普洱| 九江市| 岳普湖县| 闽侯县| 芒康县| 安阳县| 察隅县| 盐城市| 宁南县| 长治县| 新蔡县| 图木舒克市| 陇川县| 阿克陶县| 玛沁县| 社会| 卢龙县| 开鲁县| 呼玛县| 和林格尔县| 五常市| 龙山县| 巴东县| 乐平市| 砀山县| 南京市| 樟树市| 平塘县| 平江县| 将乐县| 蓝田县| 儋州市| 宁阳县|