Что такое пропс в программировании
Перейти к содержимому

Что такое пропс в программировании

  • автор:

Компоненты и свойства

Компоненты позволяют разделить пользовательский интерфейс на независимые, повторно используемые части и работать с каждой из частей отдельно. На этой странице представлено введение в идею компонентов. Здесь вы можете найти подробный справочник API по компоненту.

Концептуально компоненты похожи на функции JavaScript. Они принимают произвольные входные данные (называемые «props» или свойствами) и возвращают React-элементы, описывающие, что должно появиться на экране.

Функциональные и классовые компоненты

Самый простой способ определить компонент — написать JavaScript-функцию:

Данная функция — корректный компонент React, потому что он принимает один аргумент-объект «props» (который обозначает свойства) с данными и возвращает элемент React. Такие компоненты мы называем «функциональными», потому что они являются буквально функциями JavaScript.

Вы также можете использовать класс из ES6 для определения компонента:

Два вышеуказанных компонента эквивалентны с точки зрения React.

У классов есть дополнительные возможности, которые мы обсудим в следующих разделах. До этого момента мы будем использовать функциональные компоненты из-за их краткости.

Раньше мы сталкивались только с элементами React, представляющие DOM-теги:

Однако элементы также могут быть пользовательскими компонентами:

Когда React видит элемент, представляющий пользовательский компонент, он передаёт JSX-атрибуты этому компоненту в виде единственного объекта. Мы называем этот объект «props».

Например, этот код отображает «Привет, Сара» на странице:

Давайте посмотрим, что происходит в этом примере:

  1. Мы вызываем ReactDOM.render() с элементом <Welcome name="Сара" /> .
  2. React вызывает компонент Welcome с объектом как props .
  3. Наш компонент Welcome возвращает элемент <h1>Hello, Sara</h1> в качестве результата.
  4. React DOM эффективно обновляет DOM, чтобы соответствовать <h1>Hello, Sara</h1> .

Примечание: Всегда именуйте компоненты с заглавной буквы.

React обрабатывает компоненты, начинающиеся со строчных букв, как DOM-теги. Например, <div /> представляет HTML-тег div, но <Welcome /> представляет компонент и требует, чтобы Welcome был в области видимости.

Вы можете больше узнать о причинах, лежащих в основе этого соглашения здесь.

Компоненты могут ссылаться на другие компоненты в своём выводе. Это позволяет использовать одну и ту же абстракцию компонента для любого уровня детализации. Кнопка, форма, диалоговое окно, экран: в приложениях React все они обычно являются компонентами.

Например, мы можем создать компонент App , который многократно отрисовывает Welcome :

Как правило, в новых приложениях React есть один компонент App , который находится в самом верху иерархии компонентов. Однако, если вы интегрируете React в существующее приложение, вы можете начать снизу вверх с небольшого компонента, такого как Button , и постепенно идти вверх по иерархии представлений.

Не бойтесь разделять компоненты на более мелкие компоненты.

Например, рассмотрим этот компонент Comment :

Он принимает author (объект), text (строка) и date (дата) в качестве свойств и описывает комментарий на сайте социальных сетей.

Этот компонент может быть сложно изменить из-за вложенности, а также трудно повторно использовать отдельные его части. Давайте извлечём из него несколько компонентов.

Сначала мы извлечём Avatar :

Компонент Avatar не должен знать, что он отрисовывается внутри Comment . Вот почему мы присвоили свойству объекта props более общее имя: user , а не author .

Мы рекомендуем называть свойства объекта props с точки зрения самого компонента, а не контекста, в котором он используется.

Теперь мы можем чуть-чуть упростить Comment :

Затем мы извлечём компонент UserInfo , который отобразит Avatar рядом с именем пользователя:

Это позволяет нам упростить Comment ещё больше:

Извлечение компонентов сначала может показаться монотонной работой, но наличие палитры повторно используемых компонентов окупается в больших приложениях. Хорошее правило на этот счёт можно сформировать так — если часть пользовательского интерфейса используется несколько раз ( Button , Panel , Avatar ) или достаточно сложна сама по себе ( App , FeedStory , Comment ), то это хороший кандидат на извлечение компонента, чтобы он стал повторно используемым компонентом.

Свойства объекта props доступны только для чтения

Независимо от того, объявляете ли компонент как функцию или класс, он не должен изменять свои свойства. Рассмотрим эту функцию sum :

Такие функции называются «чистыми», потому что они не пытаются изменить свои аргументы и всегда возвращают один и тот же результат для одних и тех же входных данных.

Напротив, функция ниже — не чистая, потому что она изменяет свои входные данные:

React довольно гибкий, но имеет одно строгое правило:

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

Все React-компоненты должны вести себя как чистые функции в плане своих свойств.

Конечно, пользовательские интерфейсы приложений динамичны и меняются со временем. В следующем разделе мы представим новую концепцию «состояние». Состояние позволяет компонентам React изменять свой вывод с течением времени в ответ на действия пользователя, сетевые ответы и что-либо ещё без нарушения правила выше.

Props — JS: React

Компонент Card , который мы писали ранее, на практике бесполезен, так как не позволяет поменять тексты. А создавать на каждый конкретный блок Card свой собственный компонент — не самая хорошая идея. Это не говоря о том, что чаще всего такое просто невозможно, ведь данные подставляются динамически.

Передавать данные в компоненты можно, и делается это с помощью пропсов (props):

Как видно, снаружи пропсы передаются как атрибуты в HTML, которые внутри компонента доступны из объекта props . Причём такая передача входных данных для вас уже должна быть не в новинку. Встроенные компоненты точно так же принимают на вход пропсы, такие как className и другие.

Пропсы — очень простой механизм передачи данных в компоненты, который, как правило, не вызывает никаких сложностей. Главное, что нужно запомнить при работе с пропсами: их нельзя изменять. Во-первых, из-за принципа работы React это просто ни к чему не приведёт, во-вторых, для работы с изменяемым состоянием в React предусмотрен совершенно другой механизм, который будет рассмотрен позже.

Оператор расширения

Работая с пропсами, нередко приходится передавать множество параметров, либо эти параметры присутствуют в коде в виде объекта. В таком случае можно упростить передачу, используя оператор расширения (spread-оператор).

Код выше эквивалентен следующему примеру:

Пропсы по умолчанию

Другая задача, с которой сталкиваются разработчики — установка значений по умолчанию для пропсов (для случаев, когда какие-то пропсы не переданы). Проще всего устанавливать их прямо внутри функции render , используя такой подход:

Это сработает, но потенциально может привести к проблемам производительности (в первую очередь). Тема производительности будет рассмотрена в одном из последних уроков.

В React предусмотрен способ устанавливать значения пропсов по умолчанию. Пример:

Открыть доступ

Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно

Что такое пропс в программировании

Props представляет коллекцию значений, которые ассоциированы с компонентом. Эти значения позволяют создавать динамические компоненты, которые не зависят от жестко закодированных статических данных.

Параметр props, который передается в функцию компонента, инкапсулирует свойства объекта. В частности, свойство name и age . При рендеринге мы можем создать набор компонентов Hello, но передать в них разные данные для name и age. И таким образом, получим набор однотипной разметки html, наполненной разными данными.

Класс компонента также извне получает объект свойств, который доступен через this.props .

Использование стрелочных функций (arrow functions):

Используем компонент Hello:

При рендеринге React передает значения атрибутов в виде единого объекта «props». То есть значение из атрибута name=»Tom» перейдет в свойство props.name .

В итоге будет создана следующая страница:

Свойства Props в React

Значения по умолчанию

Мы можем определить для свойств значения по умолчанию на тот случай, если их значения не передаются извне.

Если мы применяем классы, то для установки значений применяется статическое свойство defaultProps :

При функциональном определении компонента также применяется свойство defaultProps :

И в любом из этих случаев, если мы не определим какие-то свойства для компонента, то они будут брать значения из значений по умолчанию:

Свойства по умолчанию Props defaultProps в компонентах React

Обновление props

Сам this.props представляет неизменяемый объект, который предназначен только для чтения. Поэтому не следует его изменять, например:

Если же надо время то времени изменять какие-то внутренние данные компонента, то для хранения таких данных в React предназначен объект state , который будет рассмотрен в следующей статье.

What are Props in React?

Sanje Qi

Normally you start out with React’s JSX syntax for rendering something to the browser when learning about React. Basically, JSX mixes HTML with JavaScript to get the best of both worlds.

Pretty soon you will split out your first React component.

A common question followed by this act: how to pass the data as params (parameters) from one React component to another component? That’s because you don’t want to have a component rendering static data, but pass dynamic data to your component instead. That’s where React’s props come into play. You can pass data in React by defining custom HTML attributes to which you assign your data with JSX syntax. So don’t forget the curly braces.

As you can see, the props are received in React’s class component via the this instance of the class. A common question which comes up then: Why aren’t the props received in the render methods signature? It would be similar to functional stateless components then. As for now, the team behind React considered it but didn’t change the API for React class components yet. Maybe it will be changed at some point.

In a functional stateless component, the props are received in the function signature as arguments:

Since you will find always the props in the function signature, which most of the time is only the container object of your data, but not the data to be used, you can destructure the props early in the function signature. One would call it React props destructuring:

As you have seen, props enable you to pass variables from one to another component down the component tree. In the previous example, it was only a string variable. But props can be anything from integers over objects to arrays. Even React components, but you will learn about this later. You can also define the props inline. In case of strings, you can pass props inside double quotes (or single quotes) too.

But you can also pass other data structures with inline props. In case of objects, it can be confusing for React beginners, because you have two curly braces: one for the JSX and one for the object. That’s especially confusing when passing a style object to a style attribute in React the first time.

Note: It is important to note that is could lead to performance issues because every time the component renders a new object is created again. But it can be a premature optimization as well when learning only about React.

Basically, that’s how props are passed to React components. As you may have noticed, props are only passed from top to bottom in React’s component tree. There is no way to pass props up to a parent component. We will revisit this issue later in this article. In addition, it’s important to know that React’s props are read-only. There is no way in React to set props (even though it was possible in the past). After all, props are only used to pass data from one component to another component React, but only from parent to child components down the component tree.

React Props vs. State

Passing only props from component to component doesn’t make the component interactive, because nothing is there to change the props. Props are read-only. That’s the time when React state comes into play which can be changed. The state is co-located to a React component.

In this case, the code uses a ternary operator to either show the greeting or not. You can read up this tutorial about all the conditional renderings in React. The state makes the React components interactive. You can read and write state, whereas props are read-only. Once the state changes, the component renders again. In addition, state can be passed as props to child components too.

The child component doesn’t know whether the incoming props are state or props from the parent component. The component just consumes the data as props. And the child component re-renders too once the incoming props changed.

In conclusion, every time the props or state change, the rendering mechanism of the affected component is triggered. That’s how the whole component tree becomes interactive, because after all, state is passed as props to other components, and once the state in a component changes, which may be passed as props to the child components, all affected components render again.

How to pass Props from child to parent Component?

This a common question for React beginners and the answer for it is brief: there is no way to pass props from a child to a parent component. Let’s revisit the previous example, but this time with an additional Button component for the toggle mechanism.

So far, the Button component manages its own co-located state. Since the Button component manages the isShow property, there is no way to pass it up as props to the App component. The App component needs the isShow property though for the conditional rendering of the Greeting component. At the moment, the application wouldn’t work this way. That’s the point when you have to lift state up for making it accessible for other components (in this case the App component itself) as state (or as passed props for other components).

The important ingredient is that the App component passes down a function in the props to the Button component now. The function is used for the click handler in the Button component. However, the Button doesn’t know the business logic of the function, only that it has to trigger the function when the button gets clicked. Above in the App component, the state is changed when the passed function is called, and thus all affected components, which use the changed state or consume it as props, render again. Now you can even pass the state as props to the Greeting component.

As said, there is no way passing props from a child to a parent component. But you can always pass functions from parent to child components, whereas the child components make use of these functions and the functions may change the state in a parent component above. Once the state has changed, the state is passed down as props again. All affected components will render again. For instance, the same pattern applies for having page components in your React application. Once you want to pass data from page to another in React, you can lift the state up to the component (usually App component) which has all page components as its child components. Then the data is managed as state in the top level component but still can be distributed to all child components.

React …props syntax

Another strategy for passing all props to a child component is the JavaScript spread operator. JavaScript’s spread operator in React is a useful power feature and you can read people referring to it as the React …props syntax even though it is not really a React feature but just a thing coming from JavaScript.

The props spreading can be used to spread a whole object with key value pairs down to a child component. It has the same effect as passing each value of the object by its own to the component as before. The child component gets the props the same way as before too. Another thing which builds up on top of the prop spread is the prop spread with rest.

As you can see, in the Greeting component the props are destructured but with a rest assignment which is called other in this case. So you have the subject prop but also the other prop which is essentially just an object with all the remaining properties (in this case only the description ). Now you can spread the rest of the props to the Description component, because all the relevant props for the other components (here the Title component) were separated from it.

React props with default value

In some cases you may want to pass default values as props. Historically the best approach to it was using JavaScript’s logical OR operator.

You can also inline it as prop:

However, with JavaScript language additions there are other features you can use for it. For instance JavaScript’s default parameter for the default value of the prop:

The latter is the most popular choice when using only JavaScript for the default value. However, in case you are using React’s PropTypes, it’s is also possible to pass default prop values the React way:

After all, my recommendation would be using JavaScript’s default parameter, because everyone outside of the React world understands it as well. Moreover, often you will not have React’s PropTypes in your project for making use of the PropTypes default in the first place.

React’s children prop

The children prop in React can be used for composing React components into each other. Rather than using inheritance (due to the nature of React’s class components), React embraces composition over inheritance. That’s why you can just put any string, element(s) or React component(s) in between of the opening and closing component tags.

In this case, only a string is put in between of the component tags. Then in the child component, you can make use of everything which is in between of the tags (string, element(s), component(s)), by using React’s children prop. For instance, you can just render the content of the children prop like it is done in this example. More to follow on this topic.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *