AlexKolonitsky / mifort-dev

GNU General Public License v3.0
5 stars 0 forks source link

Nick - React: The Basics #21

Open NickBerilov opened 7 years ago

NickBerilov commented 7 years ago

Concepts

React is a declarative, component-based JavaScript UI-framework. React’s core concept is that you page consists of a number of independent components, each with its own state and an array of methods. Components can be defined via JS functions:

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

or ES6 classes (which have some additional features), that extend the React.Component class:

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

Every React component has:

  1. A props object that contains a set of input parameters that are passed to the component through attributes:
    function App() {
      return (
        <div>
          <Welcome name="Sara" />
          <Welcome name="Cahal" />
          <Welcome name="Edite" />
        </div>
      );
    }

    props object is read-only, meaning all React components must act like pure functions with respect to their props.

  2. A state object, which is local, private and fully controlled by the component and represents the component's state. The only place where you can directly assign the state is the component's constructor. Component's setState() method should be used in all other cases. Changing the state via setState() also causes the component to re-render itself, which is the preferred way to update the view.
  3. A render() method that allows you to render the component on a page. Note: render() should always return a single root element.

As you could notice, the render() methods we used as an example returned a strange HTML-looking thing. This is JSX - a JS syntax extension. JSX can be split into multiple lines, and you can also embed JS expressions in it by wrapping them in singular curly braces. You can create normal HTML using JSX, as well as use any of the components that you've already declared. Any JSX object itself is also a JS expression, therefore it can be assigned to a variable, concatenated with another JSX object, etc. Note: since JSX is closer to JS than to HTML, the camelCase attribute naming convention is used, e.g. className instead of class. Finally, ReactDOM has its own render() method that renders one of your components into an existing element on the page:

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

Requirements

To start working with React you will need to:

  1. Install React. React is accessible via npm (npm install react react-dom) or Yarn (yarn add react react-dom); the react and react-dom npm packages also provide single-file distributions in dist folders, which are hosted on a CDN:
    <script src="https://unpkg.com/react@15/dist/react.min.js"></script>
    <script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>

    The create-react-app is also a good way to get started with a new React app, which allows you to create the initial structure for your future application and to optimize your app for production later:

    npm install -g create-react-app
    create-react-app my-app
    cd my-app
    npm start
  2. Install Babel. Since JSX is not innately supported by JS, and some browsers don't have ES6 support yet, you'll need to convert your code into ES5. It is possible to work with React without using ES6 classes and JSX, but those are too convenient to pass up.
NickBerilov commented 7 years ago

Концепции

React - декларативный, основанный на компонентах UI-фреймворк для JavaScript. Основная концепция React в том, что ваша страница состоит из набора независимых компонентов, у каждого из которых имеется своё состояние и набор методов. Компоненты могут быть объявлены с помощью JS-функций:

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

или ES6-классов (у которых имеются некоторые дополнительные возможности), которые населедуют от класса React.Component:

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

У каждого компонента в React есть:

  1. Объект props, который содержит набор входных параметров, которые передаются компоненту через атрибуты:

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

    Объект props доступен только для чтения, что означает, что все компоненты React должны относиться к props как чистые функции.

  2. Объект state, который является локальным, приватным и полностью контролируется компонентом, и отражает состояние компонента. Напрямую назначать state можно только в конструкторе компонента, в остальных случаях должен использоваться метод компонента setState(). Изменения состояния при помощи setState() приводит к перезагрузке компонента, что является предпочтительным способом обновления представления.

  3. Метод render(), который позволяет отобразить компонент на странице. Замечание: render() всегда должен возвращать только один корневой элемент.

Как вы могли заметить, методы render(), которые мы использовали в примерах, возвращали странную штуку, похожую на HTML. Это JSX - расширение синтаксиса JS. JSX может быть разделен на несколько строк, в него также можно встраивать JS-выражения, оборачивая их в одиночные фигурные скобки. С помощью JSX можно создавать обычный HTML, а также использовать собственные компоненты, которые уже были объявлены. Любой JSX-объект также является JS-выражением, что позволяет записать его в переменную, сложить с другим JSX-объектом и т.д. Замечание: т.к. JSX ближе к JS, чем к HTML, названия атрибутов используют нотацию camelCase, например className вместо class. И наконец, у ReactDOM есть свой метод render(), который отображает один из ваших компонентов в уже существующем элементе страницы.

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

Требования

Чтобы начать работу с React, нужно:

  1. Установить React. React доступен через npm (npm install react react-dom) или Yarn (yarn add react react-dom); npm-пакеты react and react-dom также предоставляют однофайловые дистрибутивы, которые выложены на CDN:
    <script src="https://unpkg.com/react@15/dist/react.min.js"></script>
    <script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>

    create-react-app - тоже хороший способ начать работу с новым React-приложением, который позволяет создать изначальную структуру будущего приложения и позднее оптимизировать ваше приложение:

    npm install -g create-react-app
    create-react-app my-app
    cd my-app
    npm start
  2. Установить Babel. Т.к. JSX изначально не поддерживается JS, а некоторые браузеры не поддерживают ES6, вам нужно будет конвертировать свой код в ES5. С React можно работать и без JSX и ES6-классов, но они слишком удобны, чтобы обходить их стороной.
AlexKolonitsky commented 7 years ago

Лера, проверь грамматику и можно публиковать