Documentation

1. Quick Start

1.1. Installation

React is flexible and can be used in various projects. You can use it to create new applications, but you can also gradually introduce it into existing code without rewriting it.

Here are some ways to get started:

  • try React
  • Create new application
  • Add React to an existing app

1.1.1. Try React

//EVERYTHING

1.1.2. Create a new application

Create React App is the best way to start building a new React app. It sets up your development environment so that you can use the latest JavaScript features, provide a great development experience, and optimize your applications for production. You need to have 6 or more Nodes on your machine.

npm install -g create-react-app
create-react-app my-app

cd my-app
npm start

If you have npm 5.2.0+ installed, you can use npx instead.

npx create-react-app my-app

cd my-app
npm start

Create React App doesn't handle backend logic or database, it just creates a frontend build path so you can use it with any backend. It uses build tools like Babel and webpack under the hood, but works with zero configuration.

When you're ready to deploy to production, running npm run build will create an optimized build of your app in the build folder. You can learn more about Create React App from its README and user guide.

1.1.3. Adding React to an Existing Application

//EVERYTHING

1.2. Hello World

The easiest way to get started with React is to use the Hello World sample code on CodePen. You don't need to install anything, you can open it in another tab and follow along as we walk through the examples. If you prefer to use a local development environment, please refer to the installation page.

A minimal React example looks like this:

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

It renders a title on the page: "Hello, world!".

The next few sections will walk you through using React. We'll cover the building blocks of React applications: elements and components. Once you get the hang of them, you can create complex applications from small reusable parts.

1.2.1. Tips on JavaScript

React is a JavaScript library, so it assumes a basic understanding of the JavaScript language. If you're not feeling confident, we recommend updating your JavaScript knowledge so you can keep up more easily.

We also use some ES6 syntax in the examples. We try to use it sparingly as it is still relatively new, but we encourage you to become familiar with arrow functions, classes, template literals, let and const statements. You can use the Babel REPL to inspect what ES6 code compiles to.

1.3. Introducing JSX

Consider this constant declaration:

const element = <h1>Hello, world!</h1>;

This interesting tag syntax is neither string nor HTML.

It's called JSX, and it's a syntax extension to JavaScript. We recommend using it in React to describe what a UI should look like. JSX might remind you of a templating language, but it has all the power of JavaScript.

JSX produces React "elements". We'll explore rendering them to the DOM in the next section. Below, you can find the basics of JSX you need to get started with React.

//EVERYTHING

1.4. Rendering elements

Elements are the smallest building blocks of React applications.

An element describes what you want to see on the screen:

const element = <h1>Hello, world</h1>;

Unlike browser DOM elements, React elements are ordinary objects and are easy to create. React DOM is responsible for updating the DOM to match React elements.

Notice:

One might confuse elements with the more widely known concept of "components". We'll cover components in the next section. Elements are made up of components, and we encourage you to read this section before skipping.

1.4.1. Rendering an element into the DOM

Suppose there is a <div> somewhere in the HTML file:

<div id="root"></div>

We call this the "root" DOM ​​node because everything inside it is managed by the React DOM.

React-built applications typically have only one root DOM node. If you're integrating React into an existing application, you probably have as many separate root DOM nodes as you need.

To render a React element into a root DOM node, pass two arguments to ReactDOM.render():

const element = <h1>Hello, world</h1>;
ReactDOM.render(
  element,
  document.getElementById('root')
);

Try it on CodePen

It displays "Hello, world" on the page.

1.4.2. Updating rendered elements

//EVERYTHING

1.5. Components and Properties

Components let you split your UI into independent reusable chunks and consider each chunk independently.

Conceptually, components are like JavaScript functions. They take arbitrary input (called "props") and return React elements that describe what should appear on the screen.

1.5.1. Functional and class components

The easiest way to define a component is to write a JavaScript function:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

This function is a valid React component because it accepts a single "props" (which stands for properties) data object parameter and returns a React element. We call these components "functional" because they are actually JavaScript functions.

You can also use ES6 classes to define components:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

The above two components are equivalent from a React perspective.

Classes have some additional features, which we will discuss in the next section. Until then, we'll use functional components because they're more concise.

1.5.2. Rendering a component

Previously, we only encountered React elements representing DOM markup:

const element = <div />;

However, elements can also be represented as user-defined components:

const element = <Welcome name="Sara" />;

When React sees an element representing a user-defined component, it passes JSX properties to that component as a single object. We call this object "props".

For example, this code renders "Hello, Sara" on the page:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

Try it on CodePen

Let's review what happened in this example:

  1. We call ReactDOM.render() and pass in the <Welcome name="Sara" /> element.
  2. React calls the Welcome component with {name: 'Sara'} as a property.
  3. Our Welcome component returns a <h1>Hello, Sara</h1> element as a result.
  4. React DOM effectively updates the DOM to match <h1>Hello, Sara</h1>.

admonish

Always start component names with a capital letter.

For example, <div /> represents a DOM tag, but <Welcome /> represents a component and requires Welcome to be in scope.

1.5.3. Components

Components can involve other components in their output. This allows us to use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React applications, all of these are universally represented as components.

For example, we can create an App component that renders Welcome multiple times:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Try it on CodePen

Typically, new React apps have an App component at the very top. However, if you integrate React into an existing application, you can start bottom-up with a Button-like widget and work your way up to the top of the view hierarchy.

1.5.4. Extract components

Don't be afraid to split components into smaller components.

For example, consider the following Comment component:

function Comment(props) {
  return (
    <div className="comment">
      <div className="user-info">
        <img className="avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
        />
        <div className="user-info-name">
          {props.author.name}
        </div>
      </div>
      <div className="comment-text">
        {props.text}
      </div>
      <div className="comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

Try it on CodePen

It accepts author (an object), text (a string) and date (a date) as props and describes comments on social media sites.

Because of all the nesting, this component can be hard to change, and it's hard to reuse individual parts of it. Let's extract some components from it.

First, we'll extract the Avatar:

function Avatar(props) {
  return (
    <img className="avatar"
      src={props.user.avatarUrl}
      alt={props.user.name}
    />
  );
}

Avatar does not need to know that it is rendered in Comment. That's why we gave it a more generic property name: user instead of author.

We recommend using the component's own view-named property rather than its context.

Now we can simplify Comment a bit:

function Comment(props) {
  return (
    <div className="comment">
      <div className="user-info">
        <Avatar user={props.author} />
        <div className="user-info-name">
          {props.author.name}
        </div>
      </div>
      <div className="comment-text">
        {props.text}
      </div>
      <div className="comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

Next, we'll extract a UserInfo component that will render an Avatar next to the username:

function UserInfo(props) {
  return (
    <div className="user-info">
      <Avatar user={props.user} />
      <div className="user-info-name">
        {props.user.name}
      </div>
    </div>
  );
}

This lets us simplify the Comment even further:

function Comment(props) {
  return (
    <div className="comment">
      <UserInfo user={props.author} />
      <div className="comment-text">
        {props.text}
      </div>
      <div className="comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

Try it on CodePen

Extracting components may seem like a tedious job at first, but having a palette of reusable components pays off in larger applications. A good rule of thumb is that if a part of your UI is used multiple times (Button, Panel, Avatar), or is complex enough on its own (App, Avatar), then it's a good candidate for a reusable component.

1.5.5. props are read-only

//EVERYTHING

1.6. States and Lifecycles

Consider the example of a ticking clock from the previous subsection.

So far, we've only learned one way to update the UI.

We call ReactDOM.render() to change the rendered output:

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  ReactDOM.render(
    element,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);

Try it on CodePen

In this section, we will learn how to make the Clock component truly reusable and encapsulated. It will set its own timer and update it every second.

We can start with what the encapsulated clock looks like:

function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);

Try it on CodePen

However, it ignores a key requirement: setting a timer for the Clock, updating the UI every second should be an implementation detail of the Clock.

Ideally, we'd like to let Clock update itself once it's written:

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

To achieve this, we need to add "state" to the Clock component.

State is like a property, but it is private and fully controlled by the component.

We mentioned earlier that components defined as classes have some additional properties. Local state is just that: features that are only available to the class.

1.6.1. Converting functions to classes

You can convert a functional component like Clock into a class in five steps:

  1. Create an ES6 class with the same name that inherits React.Component.
  2. Add an empty method called render().
  3. Move the function body into the render() method.
  4. In the render() method body, replace props with this.props.
  5. Remove the remaining empty function declarations.
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Try it on CodePen

Clock is now defined as a class instead of a function.

This allows us to use other features such as local state and lifecycle hooks.

1.6.2. Adding local state to a class

We will move date from props to state in three steps:

1. Replace this.props.date with this.state.date in the render() method:

class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

2. Add a class constructor that assigns the initial this.state.

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Notice how we pass props to the base constructor:

constructor(props) {
  super(props);
  this.state = {date: new Date()};
}

Class components should always call the base constructor with props.

3. Remove the date attribute from the <Clock /> element:

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

We'll add the timer code to the component itself later.
The result looks like this:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

Try it on CodePen

Next, we'll let Clock set its own timer, which will be updated every second.

1.6.3. Adding lifecycle methods to a class

In an application with many components, it is very important to release the resources occupied by the component when the component is destroyed.

We want to set a timer each time the Clock is first rendered to the DOM. In React this is called "mounting".

We also want to clear the timer whenever the DOM produced by the Clock is removed, which is called "unmounting" in React.

We can declare special methods on the component class to run some code when the component is mounted and unmounted:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {

  }

  componentWillUnmount() {

  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

These methods are called "lifecycle hooks".

The componentDidMount() hook runs after the component output has been rendered to the DOM. Here is a good place to set a timer:

componentDidMount() {
  this.timerID = setInterval(
    () => this.tick(),
    1000
  );
}

Notice how we save the timer ID in this.

While this.props is set by React itself, and this.state has a special meaning, you are free to manually add additional fields to the class if you need to store content that is not used for visual output.

If you don't use something in render(), it shouldn't be in the state either.

We will dismantle the timer in the componentWillUnmount() lifecycle hook:

componentWillUnmount() {
  clearInterval(this.timerID);
}

Finally, we will implement a method called tick() that the Clock component will run every second.

It will use this.setState() to schedule updates to the component's local state:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

Try it on CodePen

Now the clock runs every second.

Let's quickly review what's going on and the order in which the methods are called:

//EVERYTHING

1.7. Event Handling

Event handling for React elements is very similar to event handling for DOM elements. There are some syntactic differences:

  • React events are named after camelCase, not lowercase.
  • With JSX, you pass a function as the event handler, not a string.

For example, HTML:

<button onclick="activateLasers()">
  Activate Lasers
</button>

Slightly different in React:

<button onClick={activateLasers}>
  Activate Lasers
</button>

Another difference is that you cannot return false to prevent the default behavior in React. You must call preventDefault explicitly. For example, using plain HTML, to prevent the default link behavior of opening new pages, you could write:

<a href="#" onclick="console.log('The link was clicked.'); return false">
  Click me
</a>

In React, this can be replaced with:

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

Here, e is a synthetic event. React defines these synthetic events according to the W3C specification, so you don't have to worry about cross-browser compatibility. Check out the SyntheticEvent Reference Guide for more information.

When using React, there is usually no need to call addEventListener to add a listener to a DOM element after the element is created. Instead, just provide a listener when the element is initially rendered.

When you define components using ES6 classes, the usual pattern is to define event handlers as methods of the class. For example, this Toggle component renders a button that lets the user toggle between the "ON" and "OFF" states:

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

Try it on CodePen

//EVERYTHING

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325976340&siteId=291194637