-
Notifications
You must be signed in to change notification settings - Fork 47.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Create 02.3-jsx-gotchas.ru-RU.md #7217
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
--- | ||
id: jsx-gotchas-ru-RU | ||
title: Подводные камни JSX | ||
permalink: jsx-gotchas-ru-RU.html | ||
prev: jsx-spread-ru-RU.html | ||
next: interactivity-and-dynamic-uis-ru-RU.html | ||
--- | ||
|
||
JSX выглядит подобно HTML, но есть некоторые важные различия, с которыми вы можете столкнуться. | ||
|
||
> Замечание: | ||
> | ||
> О различиях, связанных с DOM, к примеру, со встроенными атрибутами `style`, читайте [здесь](/react/docs/dom-differences.html). | ||
|
||
## HTML-сущности | ||
|
||
В JSX вы можете вставлять HTML-сущности внутрь текстовых литералов: | ||
|
||
```javascript | ||
<div>Первое · Второе</div> | ||
``` | ||
|
||
Если же вы захотите отобразить HTML-сущность в динамическом содержимом, вы столкнетесь с проблемой двойного экранирования, так как все отображаемые строки экранируются React с целью предотвращения большого числа XSS-атак по умолчанию. | ||
|
||
```javascript | ||
// Плохо: показывает "Первое · Второе" | ||
<div>{'Первое · Второе'}</div> | ||
``` | ||
|
||
Есть несколько способов обойти эту проблему. Проще всего напрямую писать Unicode-символы в JavaScript. Удостоверьтесь, что файл сохранен в кодировке UTF-8 и что заданы корректные директивы UTF-8 для правильного отображения браузером. | ||
|
||
```javascript | ||
<div>{'Первое · Второе'}</div> | ||
``` | ||
|
||
Более безопасная альтернатива - найти [unicode число, соответствующее сущности](http://www.fileformat.info/info/unicode/char/b7/index.htm), и использовать его внутри строки JavaScript. | ||
|
||
```javascript | ||
<div>{'Первое \u00b7 Второе'}</div> | ||
<div>{'Первое ' + String.fromCharCode(183) + ' Второе'}</div> | ||
``` | ||
|
||
Вы можете воспользоваться смешанными массивами строк и JSX-элементов. Каждый JSX-элемент в массиве должен иметь уникальный ключ. | ||
|
||
```javascript | ||
<div>{['Первое ', <span key="middot">·</span>, ' Второе']}</div> | ||
``` | ||
|
||
В качестве крайней меры у вас есть возможность [вставить сырой HTML](/react/tips/dangerously-set-inner-html.html). | ||
|
||
```javascript | ||
<div dangerouslySetInnerHTML={{'{{'}}__html: 'Первое · Второе'}} /> | ||
``` | ||
|
||
|
||
## Нестандартные HTML-атрибуты | ||
|
||
Если в стандартные HTML-элементы вы передадите свойства, не существующие в спецификации HTML, React их не отобразит. Чтобы использовать нестандартный атрибут, укажите его с префиксом `data-`. | ||
|
||
```javascript | ||
<div data-custom-attribute="foo" /> | ||
``` | ||
|
||
Однако, произвольные атрибуты поддерживаются для пользовательских элементов (с дефисом в имени тега или атрибутом `is="..."`). | ||
|
||
```javascript | ||
<x-my-component custom-attribute="foo" /> | ||
``` | ||
|
||
Атрибуты [Web-доступности](http://www.w3.org/WAI/intro/aria), начинающиеся на `aria-`, будут отображены корректно. | ||
|
||
```javascript | ||
<div aria-hidden={true} /> | ||
``` |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This assumes #7216 is merged first.