chore(i18n,curriculum): update translations (#42659)

This commit is contained in:
camperbot
2021-06-28 20:01:36 +05:30
committed by GitHub
parent 6631e51113
commit d6955dd83a
70 changed files with 416 additions and 416 deletions

View File

@ -43,7 +43,7 @@ assert(
);
```
渲染的 `h1` 標題中應該包含一段文本,這段文本是從組件的 state 中渲染出來的。
渲染的 `h1` 標題中應該包含一段文本,這段文本是從組件的 state 中渲染出來的。
```js
async () => {

View File

@ -78,7 +78,7 @@ passport.use(new GitHubStrategy({
(data) => {
assert.match(
data,
/passport\.use.*new GitHubStrategy/gi,
/passport\.use.*new GitHubStrategy/gis,
'Passport should use a new GitHubStrategy'
);
assert.match(

View File

@ -130,7 +130,7 @@ async (getUserInput) => {
};
```
`/api/translate` 路由也應該處理美式英語和英式英語中頭銜/尊稱的縮寫方式。 例如Doctor Wright 在英式英語中縮寫爲 “Dr Wright”在美式英語中縮寫爲 “Dr. Wright"”。 查看 `/public/american-to-british-titles.js` 了應用程序應處理的不同的頭銜
`/api/translate` 路由也應該處理美式英語和英式英語中頭銜/尊稱的縮寫方式。 例如Doctor Wright 在英式英語中縮寫爲 “Dr Wright”在美式英語中縮寫爲 “Dr. Wright"”。 請參閱 `/components/american-to-british-titles.js`,瞭解程序應處理的不同標題
```js
async (getUserInput) => {

View File

@ -40,7 +40,7 @@ dashedName: sudoku-solver
- 邏輯處理一個無效的區域 (3x3 網格)
- 有效解謎字符串通過 solver
- 無效解謎字符串無法通過 solver
- solver 返回一個不完整謎題的的預期解決方案
- Solver 返回一個不完整謎題的的預期解決方案
`tests/2_functional-tests.js` 中編寫下以下測試:

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f090b6c005b0e76f068
title: 'Dictionaries: Common Applications'
title: '字典:常見應用'
challengeType: 11
videoId: f17xPfIXct0
dashedName: dictionaries-common-applications
@ -10,7 +10,7 @@ dashedName: dictionaries-common-applications
## --text--
What will the following code print?
這段代碼將打印什麼?
```python
counts = { 'quincy' : 1 , 'mrugesh' : 42, 'beau': 100, '0': 10}
@ -35,7 +35,7 @@ quincy
---
[will return error]
[將返回錯誤]
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f0c0b6c005b0e76f072
title: Networking Protocol
title: 網絡協議
challengeType: 11
videoId: c6vZGescaSc
dashedName: networking-protocol
@ -10,7 +10,7 @@ dashedName: networking-protocol
## --text--
What type of HTTP request is usually used to access a website?
通常使用哪種類型的 HTTP 請求來訪問一個網站?
## --answers--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f0c0b6c005b0e76f074
title: 'Networking: Text Processing'
title: '聯網:文本處理'
challengeType: 11
videoId: Pv_pJgVu8WI
dashedName: networking-text-processing
@ -10,7 +10,7 @@ dashedName: networking-text-processing
## --text--
Which type of encoding do most websites use?
大多數網站使用哪種編碼類型?
## --answers--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f0c0b6c005b0e76f073
title: 'Networking: Write a Web Browser'
title: '聯網:編寫一個 Web 瀏覽器'
challengeType: 11
videoId: zjyT9DaAjx4
dashedName: networking-write-a-web-browser
@ -10,7 +10,7 @@ dashedName: networking-write-a-web-browser
## --text--
What does the following code create?:
以下代碼創建了什麼?
```py
import socket
@ -30,19 +30,19 @@ mysock.close()
## --answers--
A simple web server.
一個簡單的 web 服務器
---
A simple email client.
一個簡單的 email 客戶端
---
A simple todo list.
一個簡單的待辦事項列表
---
A simple web browser.
一個簡單的 web 瀏覽器
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f170b6c005b0e76f087
title: Object Lifecycle
title: 對象的生命週期
challengeType: 11
videoId: p1r3h_AMMIM
dashedName: object-lifecycle
@ -10,7 +10,7 @@ dashedName: object-lifecycle
## --text--
What will the following program print?:
以下程序將打印什麼?
```python
class PartyAnimal:

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f080b6c005b0e76f062
title: Reading Files
title: 閱讀文件中
challengeType: 11
videoId: Fo1tW09KIwo
dashedName: reading-files
@ -10,7 +10,7 @@ dashedName: reading-files
## --text--
What is used to indicate a new line in a string?
在字符串中,用什麼來代表新的一行?
## --answers--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f180b6c005b0e76f08c
title: Relational Database Design
title: 關係數據庫設計
challengeType: 11
videoId: AqdfbrpkbHk
dashedName: relational-database-design
@ -10,7 +10,7 @@ dashedName: relational-database-design
## --text--
What is the best practice for how many times a piece of string data should be stored in a database?
對於一個字符串數據應該被保存在一個數據庫裏多少次,最佳實踐是什麼?
## --answers--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f170b6c005b0e76f08a
title: Relational Databases and SQLite
title: 關係數據庫和 SQLite
challengeType: 11
videoId: QlNod5-kFpA
dashedName: relational-databases-and-sqlite
@ -10,23 +10,23 @@ dashedName: relational-databases-and-sqlite
## --text--
Which is NOT a primary data structure in a database?
哪個不是數據庫中主要的數據結構?
## --answers--
index
指數
---
table
表格
---
row
一行
---
column
一列
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f180b6c005b0e76f08d
title: Representing Relationships in a Relational Database
title: 在關係型數據庫中表示關係
challengeType: 11
videoId: '-orenCNdC2Q'
dashedName: representing-relationships-in-a-relational-database
@ -10,23 +10,23 @@ dashedName: representing-relationships-in-a-relational-database
## --text--
What is a foreign key?
什麼是外鍵?
## --answers--
A key that is not supposed to be there.
一個不應存在於這裏的鍵
---
A key that uses non-latin characters.
一個使用非拉丁字符的鍵
---
A number that points to the primary key of an associated row in a different table.
一個指向不同表中關聯行的主鍵的數字
---
A key that the "real world" might use to look up a row.
一個在“現實世界”中可能用於查找行的鍵
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f690b6c005b0e76f095
title: Visualizing Data with Python
title: 使用 Python 可視化數據
challengeType: 11
videoId: e3lydkH0prw
dashedName: visualizing-data-with-python
@ -10,27 +10,27 @@ dashedName: visualizing-data-with-python
## --text--
Most data needs to be \_\_\_\_\_\_ before using it.
大多數數據在使用之前需要 \_\_\_\_\_\_ 。
## --answers--
converted to JSON format
轉換爲 JSON 格式
---
graphed
圖形化
---
cleaned
清理
---
memorized
記憶
---
turned into song
轉化成歌曲
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f140b6c005b0e76f07d
title: 'Web Services: JSON'
title: 'Web 服務:JSON'
challengeType: 11
videoId: ZJE-U56BppM
dashedName: web-services-json
@ -10,7 +10,7 @@ dashedName: web-services-json
## --text--
What will the following code print?:
這些代碼會打印出什麼?
```python
import json
@ -48,7 +48,7 @@ Mrugesh
---
[Error]
[Error](錯誤)
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f090b6c005b0e76f065
title: Working with Lists
title: 使用列表
challengeType: 11
videoId: lCnHfTHkhbE
dashedName: working-with-lists
@ -10,7 +10,7 @@ dashedName: working-with-lists
## --text--
Which method is used to add an item at the end of a list?
使用下列哪種方法可以在列表末尾添加元素?
## --answers--

View File

@ -43,7 +43,7 @@ assert(
);
```
渲染的 `h1` 标题中应该包含一段文本,这段文本是从组件的 state 中渲染出来的。
渲染的 `h1` 标题中应该包含一段文本,这段文本是从组件的 state 中渲染出来的。
```js
async () => {

View File

@ -78,7 +78,7 @@ passport.use(new GitHubStrategy({
(data) => {
assert.match(
data,
/passport\.use.*new GitHubStrategy/gi,
/passport\.use.*new GitHubStrategy/gis,
'Passport should use a new GitHubStrategy'
);
assert.match(

View File

@ -130,7 +130,7 @@ async (getUserInput) => {
};
```
`/api/translate` 路由也应该处理美式英语和英式英语中头衔/尊称的缩写方式。 例如Doctor Wright 在英式英语中缩写为 “Dr Wright”在美式英语中缩写为 “Dr. Wright"”。 查看 `/public/american-to-british-titles.js` 了应用程序应处理的不同的头衔
`/api/translate` 路由也应该处理美式英语和英式英语中头衔/尊称的缩写方式。 例如Doctor Wright 在英式英语中缩写为 “Dr Wright”在美式英语中缩写为 “Dr. Wright"”。 请参阅 `/components/american-to-british-titles.js`,了解程序应处理的不同标题
```js
async (getUserInput) => {

View File

@ -40,7 +40,7 @@ dashedName: sudoku-solver
- 逻辑处理一个无效的区域 (3x3 网格)
- 有效解谜字符串通过 solver
- 无效解谜字符串无法通过 solver
- solver 返回一个不完整谜题的的预期解决方案
- Solver 返回一个不完整谜题的的预期解决方案
`tests/2_functional-tests.js` 中编写下以下测试:

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f090b6c005b0e76f068
title: 'Dictionaries: Common Applications'
title: '字典:常见应用'
challengeType: 11
videoId: f17xPfIXct0
dashedName: dictionaries-common-applications
@ -10,7 +10,7 @@ dashedName: dictionaries-common-applications
## --text--
What will the following code print?
这段代码将打印什么?
```python
counts = { 'quincy' : 1 , 'mrugesh' : 42, 'beau': 100, '0': 10}
@ -35,7 +35,7 @@ quincy
---
[will return error]
[将返回错误]
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f0c0b6c005b0e76f072
title: Networking Protocol
title: 网络协议
challengeType: 11
videoId: c6vZGescaSc
dashedName: networking-protocol
@ -10,7 +10,7 @@ dashedName: networking-protocol
## --text--
What type of HTTP request is usually used to access a website?
通常使用哪种类型的 HTTP 请求来访问一个网站?
## --answers--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f0c0b6c005b0e76f074
title: 'Networking: Text Processing'
title: '联网:文本处理'
challengeType: 11
videoId: Pv_pJgVu8WI
dashedName: networking-text-processing
@ -10,7 +10,7 @@ dashedName: networking-text-processing
## --text--
Which type of encoding do most websites use?
大多数网站使用哪种编码类型?
## --answers--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f0c0b6c005b0e76f073
title: 'Networking: Write a Web Browser'
title: '联网:编写一个 Web 浏览器'
challengeType: 11
videoId: zjyT9DaAjx4
dashedName: networking-write-a-web-browser
@ -10,7 +10,7 @@ dashedName: networking-write-a-web-browser
## --text--
What does the following code create?:
以下代码创建了什么?
```py
import socket
@ -30,19 +30,19 @@ mysock.close()
## --answers--
A simple web server.
一个简单的 web 服务器
---
A simple email client.
一个简单的 email 客户端
---
A simple todo list.
一个简单的待办事项列表
---
A simple web browser.
一个简单的 web 浏览器
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f170b6c005b0e76f087
title: Object Lifecycle
title: 对象的生命周期
challengeType: 11
videoId: p1r3h_AMMIM
dashedName: object-lifecycle
@ -10,7 +10,7 @@ dashedName: object-lifecycle
## --text--
What will the following program print?:
以下程序将打印什么?
```python
class PartyAnimal:

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f080b6c005b0e76f062
title: Reading Files
title: 阅读文件中
challengeType: 11
videoId: Fo1tW09KIwo
dashedName: reading-files
@ -10,7 +10,7 @@ dashedName: reading-files
## --text--
What is used to indicate a new line in a string?
在字符串中,用什么来代表新的一行?
## --answers--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f180b6c005b0e76f08c
title: Relational Database Design
title: 关系数据库设计
challengeType: 11
videoId: AqdfbrpkbHk
dashedName: relational-database-design
@ -10,7 +10,7 @@ dashedName: relational-database-design
## --text--
What is the best practice for how many times a piece of string data should be stored in a database?
对于一个字符串数据应该被保存在一个数据库里多少次,最佳实践是什么?
## --answers--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f170b6c005b0e76f08a
title: Relational Databases and SQLite
title: 关系数据库和 SQLite
challengeType: 11
videoId: QlNod5-kFpA
dashedName: relational-databases-and-sqlite
@ -10,23 +10,23 @@ dashedName: relational-databases-and-sqlite
## --text--
Which is NOT a primary data structure in a database?
哪个不是数据库中主要的数据结构?
## --answers--
index
指数
---
table
表格
---
row
一行
---
column
一列
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f180b6c005b0e76f08d
title: Representing Relationships in a Relational Database
title: 在关系型数据库中表示关系
challengeType: 11
videoId: '-orenCNdC2Q'
dashedName: representing-relationships-in-a-relational-database
@ -10,23 +10,23 @@ dashedName: representing-relationships-in-a-relational-database
## --text--
What is a foreign key?
什么是外键?
## --answers--
A key that is not supposed to be there.
一个不应存在于这里的键
---
A key that uses non-latin characters.
一个使用非拉丁字符的键
---
A number that points to the primary key of an associated row in a different table.
一个指向不同表中关联行的主键的数字
---
A key that the "real world" might use to look up a row.
一个在“现实世界”中可能用于查找行的键
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f690b6c005b0e76f095
title: Visualizing Data with Python
title: 使用 Python 可视化数据
challengeType: 11
videoId: e3lydkH0prw
dashedName: visualizing-data-with-python
@ -10,27 +10,27 @@ dashedName: visualizing-data-with-python
## --text--
Most data needs to be \_\_\_\_\_\_ before using it.
大多数数据在使用之前需要 \_\_\_\_\_\_ 。
## --answers--
converted to JSON format
转换为 JSON 格式
---
graphed
图形化
---
cleaned
清理
---
memorized
记忆
---
turned into song
转化成歌曲
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f140b6c005b0e76f07d
title: 'Web Services: JSON'
title: 'Web 服务:JSON'
challengeType: 11
videoId: ZJE-U56BppM
dashedName: web-services-json
@ -10,7 +10,7 @@ dashedName: web-services-json
## --text--
What will the following code print?:
这些代码会打印出什么?
```python
import json
@ -48,7 +48,7 @@ Mrugesh
---
[Error]
[Error](错误)
## --video-solution--

View File

@ -1,6 +1,6 @@
---
id: 5e7b9f090b6c005b0e76f065
title: Working with Lists
title: 使用列表
challengeType: 11
videoId: lCnHfTHkhbE
dashedName: working-with-lists
@ -10,7 +10,7 @@ dashedName: working-with-lists
## --text--
Which method is used to add an item at the end of a list?
使用下列哪种方法可以在列表末尾添加元素?
## --answers--

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d4036178
title: Create a Controlled Input
title: Crea una entrada controlada
challengeType: 6
forumTopicId: 301385
dashedName: create-a-controlled-input
@ -8,23 +8,23 @@ dashedName: create-a-controlled-input
# --description--
Your application may have more complex interactions between `state` and the rendered UI. For example, form control elements for text input, such as `input` and `textarea`, maintain their own state in the DOM as the user types. With React, you can move this mutable state into a React component's `state`. The user's input becomes part of the application `state`, so React controls the value of that input field. Typically, if you have React components with input fields the user can type into, it will be a controlled input form.
Tu aplicación puede tener interacciones más complejas entre `state` y la interfaz de usuario renderizada. Por ejemplo, elementos de control de formulario para la entrada de texto, tales como `input` y `textarea`, mantienen su propio estado en el DOM como los tipos de usuario. Con React, puedes mover este estado mutable hacia el `state` de un componente de React. La entrada del usuario se convierte en parte del `state` de la aplicación, así que React controla el valor de ese campo de entrada. Por lo general, si tienes componentes de React con campos de entrada en los que el usuario puede escribir, será un formulario de entrada controlado.
# --instructions--
The code editor has the skeleton of a component called `ControlledInput` to create a controlled `input` element. The component's `state` is already initialized with an `input` property that holds an empty string. This value represents the text a user types into the `input` field.
El editor de código tiene el esqueleto de un componente llamado `ControlledInput` para crear un elemento `input` controlado. El `state` del componente ya está inicializado con una propiedad `input` que contiene una cadena vacía. Este valor representa el texto que un usuario escribe en el campo `input`.
First, create a method called `handleChange()` that has a parameter called `event`. When the method is called, it receives an `event` object that contains a string of text from the `input` element. You can access this string with `event.target.value` inside the method. Update the `input` property of the component's `state` with this new string.
Primero, crea un método llamado `handleChange()` que tiene un parámetro llamado `event`. Cuando el método es llamado, este recibe un objeto `event` que contiene una cadena de texto del elemento `input`. Puedes acceder a esta cadena con `event.target.value` dentro del método. Actualiza la propiedad `input` del `state` del componente con esta nueva cadena.
In the render method, create the `input` element above the `h4` tag. Add a `value` attribute which is equal to the `input` property of the component's `state`. Then add an `onChange()` event handler set to the `handleChange()` method.
En el método `render`, crea el elemento `input` encima de la etiqueta `h4`. Añade un atributo `value` que es igual a la propiedad `input` del `state` del componente. Luego añade un manejador de eventos `onChange()` establecido al método `handleChange()`.
When you type in the input box, that text is processed by the `handleChange()` method, set as the `input` property in the local `state`, and rendered as the value in the `input` box on the page. The component `state` is the single source of truth regarding the input data.
Cuando escribes en el cuadro de entrada, ese texto es procesado por el método `handleChange()`, establecido como la propiedad `input` en el `state` local, y renderizado como el valor en el cuadro `input` de la página. El `state` del componente es la única fuente de verdad con respecto a los datos de entrada.
Last but not least, don't forget to add the necessary bindings in the constructor.
Por último, pero no menos importante, no olvides añadir los enlaces necesarios en el constructor.
# --hints--
`ControlledInput` should return a `div` element which contains an `input` and a `p` tag.
`ControlledInput` debe devolver un elemento `div` que contiene un `input` y una etiqueta `p`.
```js
assert(
@ -39,7 +39,7 @@ assert(
);
```
The state of `ControlledInput` should initialize with an `input` property set to an empty string.
El estado de `ControlledInput` debe inicializarse con una propiedad `input` establecida a una cadena vacía.
```js
assert.strictEqual(
@ -48,7 +48,7 @@ assert.strictEqual(
);
```
Typing in the input element should update the state and the value of the input, and the `p` element should render this state as you type.
Escribir en el elemento de entrada debe actualizar el estado y el valor de la entrada, y el elemento `p` debe renderizar este estado a medida que escribas.
```js
async () => {

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d4036163
title: Create a React Component
title: Crea un componente de React
challengeType: 6
forumTopicId: 301386
dashedName: create-a-react-component
@ -8,7 +8,7 @@ dashedName: create-a-react-component
# --description--
The other way to define a React component is with the ES6 `class` syntax. In the following example, `Kitten` extends `React.Component`:
La otra forma de definir un componente React es con la sintaxis de clase de ES6 `class`. En el siguiente ejemplo, `Kitten` hereda de `React.Component`:
```jsx
class Kitten extends React.Component {
@ -24,21 +24,21 @@ class Kitten extends React.Component {
}
```
This creates an ES6 class `Kitten` which extends the `React.Component` class. So the `Kitten` class now has access to many useful React features, such as local state and lifecycle hooks. Don't worry if you aren't familiar with these terms yet, they will be covered in greater detail in later challenges. Also notice the `Kitten` class has a `constructor` defined within it that calls `super()`. It uses `super()` to call the constructor of the parent class, in this case `React.Component`. The constructor is a special method used during the initialization of objects that are created with the `class` keyword. It is best practice to call a component's `constructor` with `super`, and pass `props` to both. This makes sure the component is initialized properly. For now, know that it is standard for this code to be included. Soon you will see other uses for the constructor as well as `props`.
Esto crea una clase de ES6 `Kitten` que hereda de la clase `React.Component`. Así que la clase `Kitten` ahora tiene acceso a muchas características útiles de React, como el estado local y el ciclo de vida de los "hooks". No te preocupes si aún no estás familiarizado con estos términos, ya que se tratarán con más detalle en los desafíos posteriores. También ten en cuenta que la clase `Kitten` tiene un `constructor` definido dentro de ella que llama a `super()`. Utiliza `super()` para llamar al constructor de la clase padre, en este caso `React.Component`. El constructor es un método especial utilizado durante la inicialización de objetos que se crean con la palabra clave `class`. Es una mejor práctica llamar al `constructor` de un componente con `super`, y pasar sus propiedades `props` a ambos. Esto asegura que el componente esté inicializado correctamente. Por ahora, sepan que es estándar que se incluya este código. Pronto verás otros usos para el constructor, así como las `props`.
# --instructions--
`MyComponent` is defined in the code editor using class syntax. Finish writing the `render` method so it returns a `div` element that contains an `h1` with the text `Hello React!`.
`MyComponent` está definido en el editor de código usando la sintaxis de clase. Termina de escribir el método `render` para que devuelva un elemento `div` que contiene un `h1` con el texto `Hello React!`.
# --hints--
The React component should return a `div` element.
El componente React debe devolver un único elemento `div`.
```js
assert(Enzyme.shallow(React.createElement(MyComponent)).type() === 'div');
```
The returned `div` should render an `h1` header within it.
El `div` retornado debe renderizar un encabezado `h1` dentro de él.
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
The `h1` header should contain the string `Hello React!`.
El encabezado `h1` debe contener la cadena `Hello React!`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7dbc367417b2b2512bb1
title: Create a Simple JSX Element
title: Crea un elemento JSX simple
challengeType: 6
forumTopicId: 301390
dashedName: create-a-simple-jsx-element
@ -8,29 +8,29 @@ dashedName: create-a-simple-jsx-element
# --description--
**Intro:** React is an Open Source view library created and maintained by Facebook. It's a great tool to render the User Interface (UI) of modern web applications.
React es una librería de vistas de código abierto creada y mantenida por Facebook. Es una gran herramienta para hacer la interfaz de usuario (UI) de aplicaciones web modernas.
React uses a syntax extension of JavaScript called JSX that allows you to write HTML directly within JavaScript. This has several benefits. It lets you use the full programmatic power of JavaScript within HTML, and helps to keep your code readable. For the most part, JSX is similar to the HTML that you have already learned, however there are a few key differences that will be covered throughout these challenges.
React usa una extensión de sintaxis de JavaScript llamada JSX que te permite escribir HTML directamente dentro de JavaScript. Esto tiene muchos beneficios. Te permite utilizar el poder programático completo de JavaScript dentro de HTML, y ayuda a mantener tu código legible. En su mayor parte, JSX es similar al HTML que ya has aprendido. Sin embargo, hay algunas diferencias clave que se abordarán a lo largo de estos desafíos.
For instance, because JSX is a syntactic extension of JavaScript, you can actually write JavaScript directly within JSX. To do this, you simply include the code you want to be treated as JavaScript within curly braces: `{ 'this is treated as JavaScript code' }`. Keep this in mind, since it's used in several future challenges.
Por ejemplo, dado que JSX es una extensión sintáctica de JavaScript, se puede escribir JavaScript directamente dentro de JSX. Para hacer esto, simplemente incluye el código que deseas que sea tratado como JavaScript entre llaves: `{ 'this is treated as JavaScript code' }`. Ten esto en cuenta, ya que se utiliza en varios desafíos futuros.
However, because JSX is not valid JavaScript, JSX code must be compiled into JavaScript. The transpiler Babel is a popular tool for this process. For your convenience, it's already added behind the scenes for these challenges. If you happen to write syntactically invalid JSX, you will see the first test in these challenges fail.
Sin embargo, debido a que JSX no es JavaScript válido, el código JSX debe ser compilado en JavaScript. El transpilador Babel es una herramienta muy popular para este proceso. Para tu comodidad, ya se ha añadido tras bambalinas para estos desafíos. Si escribes JSX no válido sintácticamente, verás que la primera prueba de estos desafíos falla.
It's worth noting that under the hood the challenges are calling `ReactDOM.render(JSX, document.getElementById('root'))`. This function call is what places your JSX into React's own lightweight representation of the DOM. React then uses snapshots of its own DOM to optimize updating only specific parts of the actual DOM.
Vale la pena señalar que por debajo los desafíos están llamando `ReactDOM.render(JSX, document.getElementById('root'))`. Esta llamada de función es la que coloca tu JSX en la representación ligera del DOM de React. React entonces utiliza capturas instantáneas de su propio DOM para optimizar actualizando sólo partes específicas del DOM.
# --instructions--
**Instructions:** The current code uses JSX to assign a `div` element to the constant `JSX`. Replace the `div` with an `h1` element and add the text `Hello JSX!` inside it.
El código actual utiliza JSX para asignar un elemento `div` a la constante `JSX`. Reemplaza el `div` por un elemento `h1` y añade el texto `Hello JSX!` dentro de él.
# --hints--
The constant `JSX` should return an `h1` element.
La constante `JSX` debe devolver un elemento `h1`.
```js
assert(JSX.type === 'h1');
```
The `h1` tag should include the text `Hello JSX!`
La etiqueta `h1` debe incluir el texto `Hello JSX!`
```js
assert(Enzyme.shallow(JSX).contains('Hello JSX!'));

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d4036170
title: Create a Stateful Component
title: Crea un componente de estado
challengeType: 6
forumTopicId: 301391
dashedName: create-a-stateful-component
@ -8,25 +8,25 @@ dashedName: create-a-stateful-component
# --description--
One of the most important topics in React is `state`. State consists of any data your application needs to know about, that can change over time. You want your apps to respond to state changes and present an updated UI when necessary. React offers a nice solution for the state management of modern web applications.
Uno de los temas más importantes en React es `state`. El estado consiste en cualquier dato que tu aplicación necesite conocer y que pueda cambiar con el tiempo. Quieres que tus aplicaciones respondan a los cambios de estado y presenten una interfaz de usuario actualizada cuando sea necesario. React ofrece una buena solución para el manejo de estado de aplicaciones web modernas.
You create state in a React component by declaring a `state` property on the component class in its `constructor`. This initializes the component with `state` when it is created. The `state` property must be set to a JavaScript `object`. Declaring it looks like this:
Creas un estado en un componente de React declarando una propiedad `state` en la clase del componente en su `constructor`. Esto inicializa el componente con `state` cuando se crea. La propiedad `state` debe establecerse en un `object` de JavaScript. Declararlo se ve así:
```jsx
this.state = {
// describe your state here
}
```
You have access to the `state` object throughout the life of your component. You can update it, render it in your UI, and pass it as props to child components. The `state` object can be as complex or as simple as you need it to be. Note that you must create a class component by extending `React.Component` in order to create `state` like this.
Tienes acceso al objeto `state` a lo largo de la vida de tu componente. Puedes actualizarlo, renderizarlo en tu interfaz de usuario y pasarlo como propiedades a componentes hijos. El objeto `state` puede ser tan complejo o simple como lo necesites. Ten en cuenta que debes crear un componente de clase heredando `React.Component` para crear un `state` como este.
# --instructions--
There is a component in the code editor that is trying to render a `name` property from its `state`. However, there is no `state` defined. Initialize the component with `state` in the `constructor` and assign your name to a property of `name`.
Hay un componente en el editor de código que está intentando renderizar una propiedad `name` desde su `state`. Sin embargo, no hay ningún `state` definido. Inicializa el componente con `state` en el `constructor` y asigna tu nombre a una propiedad de `name`.
# --hints--
`StatefulComponent` should exist and render.
`StatefulComponent` debe existir y renderizar.
```js
assert(
@ -39,7 +39,7 @@ assert(
);
```
`StatefulComponent` should render a `div` and an `h1` element.
`StatefulComponent` debe renderizar un `div` y un elemento `h1`.
```js
assert(
@ -55,7 +55,7 @@ assert(
);
```
The state of `StatefulComponent` should be initialized with a property `name` set to a string.
El estado de `StatefulComponent` debe inicializarse con una propiedad `name` establecida a una cadena.
```js
assert(
@ -71,7 +71,7 @@ assert(
);
```
The property `name` in the state of `StatefulComponent` should render in the `h1` element.
La propiedad `name` en el estado de `StatefulComponent` debe renderizarse en el elemento `h1`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d403618a
title: Use Array.map() to Dynamically Render Elements
title: Usare Array.map() per presentare dinamicamente gli elementi
challengeType: 6
forumTopicId: 301417
dashedName: use-array-map-to-dynamically-render-elements
@ -8,21 +8,21 @@ dashedName: use-array-map-to-dynamically-render-elements
# --description--
Conditional rendering is useful, but you may need your components to render an unknown number of elements. Often in reactive programming, a programmer has no way to know what the state of an application is until runtime, because so much depends on a user's interaction with that program. Programmers need to write their code to correctly handle that unknown state ahead of time. Using `Array.map()` in React illustrates this concept.
Il rendering condizionale è utile, ma potresti aver bisogno che i tuoi componenti presentino un numero sconosciuto di elementi. Spesso nella programmazione reattiva, un programmatore non ha modo di sapere qual è lo stato di un'applicazione fino al runtime, perché molto dipende dall'interazione di un utente con quel programma. I programmatori devono quindi scrivere il loro codice per gestire correttamente quello stato sconosciuto prima di conoscerlo. L'uso di `Array.map()` in React illustra questo concetto.
For example, you create a simple "To Do List" app. As the programmer, you have no way of knowing how many items a user might have on their list. You need to set up your component to dynamically render the correct number of list elements long before someone using the program decides that today is laundry day.
Creiamo ad esempio una semplice app "To Do List". Come programmatore, non hai modo di sapere quanti elementi un utente potrebbe avere nella sua lista. È necessario impostare il componente per presentare dinamicamente il numero corretto di elementi della lista molto prima che qualcuno che utilizza il programma decida che oggi è giorno di bucato.
# --instructions--
The code editor has most of the `MyToDoList` component set up. Some of this code should look familiar if you completed the controlled form challenge. You'll notice a `textarea` and a `button`, along with a couple of methods that track their states, but nothing is rendered to the page yet.
Nell'editor di codice troverai il componente `MyToDoList` quasi completamente configurato. Alcune parti di questo codice dovrebbero esserti familiari se hai completato la sfida del modulo controllato. Noterai una `textarea` e un `button`, insieme a un paio di metodi che tracciano i loro stati, ma per il momento niente è ancora presentato nella pagina.
Inside the `constructor`, create a `this.state` object and define two states: `userInput` should be initialized as an empty string, and `toDoList` should be initialized as an empty array. Next, delete the comment in the `render()` method next to the `items` variable. In its place, map over the `toDoList` array stored in the component's internal state and dynamically render a `li` for each item. Try entering the string `eat, code, sleep, repeat` into the `textarea`, then click the button and see what happens.
All'interno del `constructor`, crea un oggetto `this.state` e definisci due stati: `userInput` dovrebbe essere inizializzato con una stringa vuota, e `toDoList` dovrebbe essere inizializzato con un array vuoto. Successivamente, elimina il commento nel metodo `render()` accanto alla variabile `items`. Al suo posto, mappa l'array `toDoList` memorizzato nello stato interno del componente e presenta dinamicamente un `li` per ogni elemento. Prova ad inserire la stringa `eat, code, sleep, repeat` nella `textarea`, quindi fai clic sul bottone per vedere cosa succede.
**Note:** You may know that all sibling child elements created by a mapping operation like this do need to be supplied with a unique `key` attribute. Don't worry, this is the topic of the next challenge.
**Nota:** Forse sai già che tutti gli elementi figli (e fratelli tra loro) creati da un'operazione di mappatura come questa devono essere forniti con un attributo `key` univoco. Non ti preoccupare, questo è il tema della prossima sfida.
# --hints--
The MyToDoList component should exist and render to the page.
Il componente MyToDoList dovrebbe esistere ed essere presentato nella pagina.
```js
assert(
@ -33,7 +33,7 @@ assert(
);
```
The first child of `MyToDoList` should be a `textarea` element.
Il primo figlio di `MyToDoList` dovrebbe essere un elemento `textarea`.
```js
assert(
@ -47,7 +47,7 @@ assert(
);
```
The second child of `MyToDoList` should be a `br` element.
Il secondo figlio di `MyToDoList` dovrebbe essere un elemento `br`.
```js
assert(
@ -60,7 +60,7 @@ assert(
);
```
The third child of `MyToDoList` should be a `button` element.
Il terzo figlio di `MyToDoList` dovrebbe essere un elemento `button`.
```js
assert(
@ -74,7 +74,7 @@ assert(
);
```
The state of `MyToDoList` should be initialized with `toDoList` as an empty array.
Lo stato di `MyToDoList` dovrebbe essere inizializzato con `toDoList` come un array vuoto.
```js
assert(
@ -89,7 +89,7 @@ assert(
);
```
The state of `MyToDoList` should be initialized with `userInput` as an empty string.
Lo stato di `MyToDoList` dovrebbe essere inizializzato con `userInput` come una stringa vuota.
```js
assert(
@ -104,7 +104,7 @@ assert(
);
```
When the `Create List` button is clicked, the `MyToDoList` component should dynamically return an unordered list that contains a list item element for every item of a comma-separated list entered into the `textarea` element.
Quando viene cliccato il bottone `Create List`, il componente `MyToDoList` dovrebbe restituire dinamicamente una lista non ordinata che contiene un li (list item) per ogni elemento di una lista separata da virgole inserito nell'elemento `textarea`.
```js
(() => {

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d403616b
title: Use Default Props
title: Usare le proprietà predefinite
challengeType: 6
forumTopicId: 301418
dashedName: use-default-props
@ -8,15 +8,15 @@ dashedName: use-default-props
# --description--
React also has an option to set default props. You can assign default props to a component as a property on the component itself and React assigns the default prop if necessary. This allows you to specify what a prop value should be if no value is explicitly provided. For example, if you declare `MyComponent.defaultProps = { location: 'San Francisco' }`, you have defined a location prop that's set to the string `San Francisco`, unless you specify otherwise. React assigns default props if props are undefined, but if you pass `null` as the value for a prop, it will remain `null`.
React ha anche un'opzione per impostare props predefinite. È possibile assegnare props predefinite a un componente come una proprietà del componente stesso, in modo che React le assegni quando necessario. Questo ti permette di specificare quale valore dovrebbe avere una prop se nessun valore è esplicitamente fornito. Ad esempio, se dichiari `MyComponent.defaultProps = { location: 'San Francisco' }`, hai definito una prop location impostata sulla stringa `San Francisco`, a meno che non specifichi diversamente. React assegna le prop di default se non sono definite, ma se passi `null` come valore per una prop, essa rimarrà pari a `null`.
# --instructions--
The code editor shows a `ShoppingCart` component. Define default props on this component which specify a prop `items` with a value of `0`.
L'editor di codice mostra un componente `ShoppingCart`. Definisci gli elementi predefiniti su questo componente in modo che specifichino una prop `items` con un valore di `0`.
# --hints--
The `ShoppingCart` component should render.
Il componente `ShoppingCart` dovrebbe essere presentato.
```js
assert(
@ -27,7 +27,7 @@ assert(
);
```
The `ShoppingCart` component should have a default prop of `{ items: 0 }`.
Il componente `ShoppingCart` dovrebbe avere una prop predefinita di `{ items: 0 }`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d403616d
title: Use PropTypes to Define the Props You Expect
title: Usare i PropTypes per definire le Prop attese
challengeType: 6
forumTopicId: 301419
dashedName: use-proptypes-to-define-the-props-you-expect
@ -8,25 +8,25 @@ dashedName: use-proptypes-to-define-the-props-you-expect
# --description--
React provides useful type-checking features to verify that components receive props of the correct type. For example, your application makes an API call to retrieve data that you expect to be in an array, which is then passed to a component as a prop. You can set `propTypes` on your component to require the data to be of type `array`. This will throw a useful warning when the data is of any other type.
React fornisce utili funzioni di verifica del tipo per verificare che i componenti ricevano proprietà del tipo corretto. Ad esempio, la tua applicazione effettua una chiamata API per recuperare dei dati che ti aspetti essere in un array, che viene poi passato a un componente come proprietà. Puoi impostare `propTypes` sul tuo componente per richiedere che i dati siano di tipo `array`. Questo generà un avviso utile quando i dati saranno di qualsiasi altro tipo.
It's considered a best practice to set `propTypes` when you know the type of a prop ahead of time. You can define a `propTypes` property for a component in the same way you defined `defaultProps`. Doing this will check that props of a given key are present with a given type. Here's an example to require the type `function` for a prop called `handleClick`:
È considerata una buona pratica impostare `propTypes` quando si conosce il tipo di una prop in anticipo. Puoi definire una proprietà `propTypes` per un componente nello stesso modo in cui hai definito `defaultProps`. In questo modo si verificherà che la prop con una data chiave sia presenti con un dato tipo. Ecco un esempio per richiedere il tipo `function` per una prop chiamata `handleClick`:
```js
MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }
```
In the example above, the `PropTypes.func` part checks that `handleClick` is a function. Adding `isRequired` tells React that `handleClick` is a required property for that component. You will see a warning if that prop isn't provided. Also notice that `func` represents `function`. Among the seven JavaScript primitive types, `function` and `boolean` (written as `bool`) are the only two that use unusual spelling. In addition to the primitive types, there are other types available. For example, you can check that a prop is a React element. Please refer to the [documentation](https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type) for all of the options.
Nell'esempio sopra, la parte `PropTypes.func` controlla che `handleClick` sia una funzione. Aggiungendo `isRequired` si dice a React che `handleClick` è una proprietà richiesta per quel componente. Se quella prop non è fornita vedrai un avviso. Nota anche che `func` rappresenta `function`. Tra i sette tipi primitivi JavaScript, `function` e `boolean` (scritto come `bool`) sono gli unici che usano un'ortografia insolita. Oltre ai tipi primitivi, ci sono altri tipi disponibili. Ad esempio, puoi controllare che una prop sia un elemento React. Fai riferimento alla [documentazione](https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type) per tutte le opzioni.
**Note:** As of React v15.5.0, `PropTypes` is imported independently from React, like this: `import PropTypes from 'prop-types';`
**Nota:** A partire da React v15.5.0, `PropTypes` viene importato indipendentemente da React, in questo modo: `import PropTypes from 'prop-types';`
# --instructions--
Define `propTypes` for the `Items` component to require `quantity` as a prop and verify that it is of type `number`.
Definisci `propTypes` in modo che il componente `Items` richieda `quantity` come prop e verifica che sia di tipo `number`.
# --hints--
The `ShoppingCart` component should render.
Il componente `ShoppingCart` dovrebbe essere presentato.
```js
assert(
@ -37,7 +37,7 @@ assert(
);
```
The `Items` component should render.
Il componente `Items` dovrebbe essere presentato.
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
The `Items` component should include a `propTypes` check to require a value for `quantity` and ensure that its value is a number.
Il componente `Items` dovrebbe includere un controllo di `propTypes` per richiedere un valore per `quantity` e assicurarsi che il suo valore sia un numero.
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d4036165
title: Use React to Render Nested Components
title: Usare React per presentare i componenti annidati
challengeType: 6
forumTopicId: 301420
dashedName: use-react-to-render-nested-components
@ -8,23 +8,23 @@ dashedName: use-react-to-render-nested-components
# --description--
The last challenge showed a simple way to compose two components, but there are many different ways you can compose components with React.
L'ultima sfida ha mostrato un modo semplice per comporre due componenti, ma ci sono molti modi diversi per comporre componenti con React.
Component composition is one of React's powerful features. When you work with React, it is important to start thinking about your user interface in terms of components like the App example in the last challenge. You break down your UI into its basic building blocks, and those pieces become the components. This helps to separate the code responsible for the UI from the code responsible for handling your application logic. It can greatly simplify the development and maintenance of complex projects.
La composizione dei componenti è una delle potenti caratteristiche di React. Quando si lavora con React, è importante iniziare a pensare alla tua interfaccia utente in termini di componenti come abbiamo visto nell'App di esempio dell'ultima sfida. Scomponi la tua interfaccia utente nei suoi blocchi di base e quei pezzi diventeranno i componenti. Questo aiuta a separare il codice responsabile dell'interfaccia utente dal codice responsabile della gestione della logica dell'applicazione. Questo può semplificare notevolmente lo sviluppo e il mantenimento di progetti complessi.
# --instructions--
There are two functional components defined in the code editor, called `TypesOfFruit` and `Fruits`. Take the `TypesOfFruit` component and compose it, or *nest* it, within the `Fruits` component. Then take the `Fruits` component and nest it within the `TypesOfFood` component. The result should be a child component, nested within a parent component, which is nested within a parent component of its own!
Ci sono due componenti funzionali definiti nell'editor di codice, chiamati `TypesOfFruit` e `Fruits`. Prendi il componente `TypesOfFruit` e componilo o *annidalo* all'interno del componente `Fruits`. Quindi prendi il componente `Fruits` e annidalo all'interno del componente `TypesOfFood`. Il risultato dovrebbe essere un componente figlio, annidato all'interno di un componente genitore, che è annidato all'interno di un componente genitore proprio!
# --hints--
The `TypesOfFood` component should return a single `div` element.
Il componente `TypesOfFood` dovrebbe restituire un singolo elemento `div`.
```js
assert(Enzyme.shallow(React.createElement(TypesOfFood)).type() === 'div');
```
The `TypesOfFood` component should return the `Fruits` component.
Il componente `TypesOfFood` dovrebbe restituire il componente `Fruits`.
```js
assert(
@ -33,7 +33,7 @@ assert(
);
```
The `Fruits` component should return the `TypesOfFruit` component.
Il componente `Fruits` dovrebbe restituire il componente `TypesOfFruit`.
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
The `TypesOfFruit` component should return the `h2` and `ul` elements.
Il componente `TypesOfFruit` dovrebbe restituire gli elementi `h2` e `ul`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d4036176
title: Use State to Toggle an Element
title: Usare lo stato per attivare e disattivare un elemento
challengeType: 6
forumTopicId: 301421
dashedName: use-state-to-toggle-an-element
@ -8,7 +8,7 @@ dashedName: use-state-to-toggle-an-element
# --description--
Sometimes you might need to know the previous state when updating the state. However, state updates may be asynchronous - this means React may batch multiple `setState()` calls into a single update. This means you can't rely on the previous value of `this.state` or `this.props` when calculating the next value. So, you should not use code like this:
A volte potrebbe essere necessario conoscere lo stato precedente quando si aggiorna lo stato. Tuttavia, gli aggiornamenti dello stato possono essere asincroni - questo significa che React può raggruppare più chiamate `setState()` in un singolo aggiornamento. Questo significa che non puoi fare affidamento sul valore precedente di `this.state` o di `this.props` quando calcoli il valore successivo. Quindi, non si dovrebbe utilizzare il codice in questo modo:
```jsx
this.setState({
@ -16,7 +16,7 @@ this.setState({
});
```
Instead, you should pass `setState` a function that allows you to access state and props. Using a function with `setState` guarantees you are working with the most current values of state and props. This means that the above should be rewritten as:
Invece, dovresti passare a `setState` una funzione che ti permetta di accedere a stato e props. L'utilizzo di una funzione con `setState` garantisce che si sta lavorando con i valori più aggiornati di stato e props. Questo significa che quanto sopra dovrebbe essere riscritto come:
```jsx
this.setState((state, props) => ({
@ -24,7 +24,7 @@ this.setState((state, props) => ({
}));
```
You can also use a form without `props` if you need only the `state`:
Puoi anche usare una forma senza `props` se hai bisogno solo dello `state`:
```jsx
this.setState(state => ({
@ -32,21 +32,21 @@ this.setState(state => ({
}));
```
Note that you have to wrap the object literal in parentheses, otherwise JavaScript thinks it's a block of code.
Nota che devi avvolgere l'oggetto letterale tra parentesi, altrimenti JavaScript pensa che sia un blocco di codice.
# --instructions--
`MyComponent` has a `visibility` property which is initialized to `false`. The render method returns one view if the value of `visibility` is true, and a different view if it is false.
`MyComponent` ha una proprietà `visibility` che viene inizializzata a `false`. Il metodo render restituisce una vista se il valore di `visibility` è true, e una vista diversa se è false.
Currently, there is no way of updating the `visibility` property in the component's `state`. The value should toggle back and forth between true and false. There is a click handler on the button which triggers a class method called `toggleVisibility()`. Pass a function to `setState` to define this method so that the `state` of `visibility` toggles to the opposite value when the method is called. If `visibility` is `false`, the method sets it to `true`, and vice versa.
Attualmente, non c'è modo di aggiornare la proprietà `visibility` nello `state` del componente. Il valore dovrebbe commutare avanti e indietro tra vero e falso. C'è un gestore di click sul bottone che attiva un metodo di classe chiamato `toggleVisibility()`. Passa una funzione a `setState` per definire questo metodo in modo che lo `state` di `visibility` commuti al valore opposto quando viene chiamato il metodo. Se `visibility` è `false`, il metodo lo imposta a `true`, e viceversa.
Finally, click the button to see the conditional rendering of the component based on its `state`.
Infine, fai click sul pulsante per vedere il rendering condizionale del componente in base al suo `state`.
**Hint:** Don't forget to bind the `this` keyword to the method in the `constructor`!
**Suggerimento:** Non dimenticare di associare la parola chiave `this` al metodo nel `constructor`!
# --hints--
`MyComponent` should return a `div` element which contains a `button`.
`MyComponent` dovrebbe restituire un elemento `div` che contiene un `button`.
```js
assert.strictEqual(
@ -56,7 +56,7 @@ assert.strictEqual(
);
```
The state of `MyComponent` should initialize with a `visibility` property set to `false`.
Lo stato di `MyComponent` dovrebbe essere inizializzato con una proprietà `visibility` impostata su `false`.
```js
assert.strictEqual(
@ -65,7 +65,7 @@ assert.strictEqual(
);
```
Clicking the button element should toggle the `visibility` property in state between `true` and `false`.
Cliccando sul bottone si dovrebbe commutare la proprietà `visibility` nello stato, tra i due valori `true` e `false`.
```js
(() => {
@ -89,7 +89,7 @@ Clicking the button element should toggle the `visibility` property in state bet
})();
```
An anonymous function should be passed to `setState`.
Una funzione anonima dovrebbe essere passata a `setState`.
```js
const paramRegex = '[a-zA-Z$_]\\w*(,[a-zA-Z$_]\\w*)?';
@ -104,7 +104,7 @@ assert(
);
```
`this` should not be used inside `setState`
`this` non dovrebbe essere usato all'interno di `setState`
```js
assert(!/this\.setState\([^}]*this/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d403617d
title: Use the Lifecycle Method componentDidMount
title: Usare il metodo del ciclo di vita componentDidMount
challengeType: 6
forumTopicId: 301422
dashedName: use-the-lifecycle-method-componentdidmount
@ -8,17 +8,17 @@ dashedName: use-the-lifecycle-method-componentdidmount
# --description--
Most web developers, at some point, need to call an API endpoint to retrieve data. If you're working with React, it's important to know where to perform this action.
La maggior parte degli sviluppatori web, a un certo punto, deve chiamare un'API endpoint per recuperare i dati. Se stai lavorando con React, è importante sapere dove eseguire questa azione.
The best practice with React is to place API calls or any calls to your server in the lifecycle method `componentDidMount()`. This method is called after a component is mounted to the DOM. Any calls to `setState()` here will trigger a re-rendering of your component. When you call an API in this method, and set your state with the data that the API returns, it will automatically trigger an update once you receive the data.
La migliore pratica con React è quella di effettuare chiamate API o qualsiasi chiamata al server nel metodo del ciclo di vita `componentDidMount()`. Questo metodo viene chiamato dopo che un componente è stato montato nel DOM. Qualsiasi chiamata a `setState()` qui attiverà un re-rendering del tuo componente. Quando chiami un'API in questo metodo, e imposti il tuo stato con i dati che l'API restituisce, si attiverà automaticamente un aggiornamento una volta che i dati saranno ricevuti.
# --instructions--
There is a mock API call in `componentDidMount()`. It sets state after 2.5 seconds to simulate calling a server to retrieve data. This example requests the current total active users for a site. In the render method, render the value of `activeUsers` in the `h1` after the text `Active Users:`. Watch what happens in the preview, and feel free to change the timeout to see the different effects.
C'è una chiamata API finta in `componentDidMount()`. Essa imposta lo stato dopo 2.5 secondi per simulare la chiamata a un server per recuperare i dati. Questo esempio richiede il numero di utenti attivi per un sito. Nel metodo render, presenta il valore di `activeUsers` nell'`h1` dopo il testo `Active Users:`. Guarda cosa succede nell'anteprima e sentiti libero di cambiare il timeout per vedere i diversi effetti.
# --hints--
`MyComponent` should render a `div` element which wraps an `h1` tag.
`MyComponent` dovrebbe mostrare un elemento `div` che contiene un tag `h1`.
```js
assert(
@ -32,7 +32,7 @@ assert(
);
```
Component state should be updated with a timeout function in `componentDidMount`.
Lo stato del componente dovrebbe essere aggiornato con una funzione timeout in `componentDidMount`.
```js
assert(
@ -45,7 +45,7 @@ assert(
);
```
The `h1` tag should render the `activeUsers` value from `MyComponent`'s state.
Il tag `h1` dovrebbe presentare il valore `activeUsers` dallo stato di `MyComponent`.
```js
(() => {

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d403617c
title: Use the Lifecycle Method componentWillMount
title: Usare il metodo del ciclo di vita componentWillMount
challengeType: 6
forumTopicId: 301423
dashedName: use-the-lifecycle-method-componentwillmount
@ -8,17 +8,17 @@ dashedName: use-the-lifecycle-method-componentwillmount
# --description--
React components have several special methods that provide opportunities to perform actions at specific points in the lifecycle of a component. These are called lifecycle methods, or lifecycle hooks, and allow you to catch components at certain points in time. This can be before they are rendered, before they update, before they receive props, before they unmount, and so on. Here is a list of some of the main lifecycle methods: `componentWillMount()` `componentDidMount()` `shouldComponentUpdate()` `componentDidUpdate()` `componentWillUnmount()` The next several lessons will cover some of the basic use cases for these lifecycle methods.
I componenti React hanno diversi metodi speciali che offrono l'opportunità di eseguire azioni in punti specifici del ciclo di vita di un componente. Questi sono chiamati metodi del ciclo di vita, o hooks (ganci) del ciclo di vita, e consentono di intercettare i componenti in determinati istanti. Ad esempio prima che sia fatto il render del componente, prima di aggiornarlo, prima di ricevere le prop, prima di smontarlo, e così via. Ecco un elenco di alcuni dei principali metodi del ciclo di vita: `componentWillMount()` `componentDidMount()` `shouldComponentUpdate()` `componentDidUpdate()` `componentWillUnmount()` Le prossime lezioni copriranno alcuni dei casi di base per questi metodi del ciclo di vita.
**Note:** The `componentWillMount` Lifecycle method will be deprecated in a future version of 16.X and removed in version 17. [(Source)](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html)
**Nota:** Il metodo del ciclo di vita `componentWillMount` sarà deprecato in una versione futura di 16.X e rimosso nella versione 17. [(Fonte)](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html)
# --instructions--
The `componentWillMount()` method is called before the `render()` method when a component is being mounted to the DOM. Log something to the console within `componentWillMount()` - you may want to have your browser console open to see the output.
Il metodo `componentWillMount()` viene chiamato prima del metodo `render()` quando un componente viene montato sul DOM. Scrivi qualcosa nella console all'interno di `componentWillMount()` - potresti aprire la console del browser per vedere l'output.
# --hints--
`MyComponent` should render a `div` element.
`MyComponent` dovrebbe presentare un elemento `div`.
```js
assert(
@ -29,7 +29,7 @@ assert(
);
```
`console.log` should be called in `componentWillMount`.
`console.log` dovrebbe essere chiamato in `componentWillMount`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d4036168
title: Write a React Component from Scratch
title: Scrivere un componente React da zero
challengeType: 6
forumTopicId: 301424
dashedName: write-a-react-component-from-scratch
@ -8,17 +8,17 @@ dashedName: write-a-react-component-from-scratch
# --description--
Now that you've learned the basics of JSX and React components, it's time to write a component on your own. React components are the core building blocks of React applications so it's important to become very familiar with writing them. Remember, a typical React component is an ES6 `class` which extends `React.Component`. It has a render method that returns HTML (from JSX) or `null`. This is the basic form of a React component. Once you understand this well, you will be prepared to start building more complex React projects.
Ora che hai imparato le basi dei componenti JSX e React, è il momento di scrivere un componente da solo. I componenti di React sono gli elementi fondamentali delle applicazioni React quindi è importante acquisire familiarità con la loro scrittura. Ricorda, un componente React tipico è una `class` ES6 che estende `React.Component`. Essa ha un metodo render che restituisce HTML (da JSX) o `null`. Questa è la forma di base di una componente React. Una volta che avrai capito bene questo, sarai pronto a iniziare a costruire progetti React più complessi.
# --instructions--
Define a class `MyComponent` that extends `React.Component`. Its render method should return a `div` that contains an `h1` tag with the text: `My First React Component!` in it. Use this text exactly, the case and punctuation matter. Make sure to call the constructor for your component, too.
Definisci una classe `MyComponent` che estenda `React.Component`. Il suo metodo render dovrebbe restituire un `div` che contiene un tag `h1` con il testo: `My First React Component!` in esso. Usa questo testo esattamente, le maiuscole e la punteggiatura contano. Assicurati di chiamare anche il costruttore per il tuo componente.
Render this component to the DOM using `ReactDOM.render()`. There is a `div` with `id='challenge-node'` available for you to use.
Presenta questo componente nel DOM usando `ReactDOM.render()`. C'è un `div` con `id='challenge-node'` pronto all'uso per te.
# --hints--
There should be a React component called `MyComponent`.
Ci dovrebbe essere un componente React chiamato `MyComponent`.
```js
(getUserInput) =>
@ -29,7 +29,7 @@ There should be a React component called `MyComponent`.
);
```
`MyComponent` should contain an `h1` tag with text `My First React Component!` Case and punctuation matter.
`MyComponent` dovrebbe contenere un tag `h1` con testo `My First React Component!` Maiuscole e punteggiatura contano.
```js
assert(
@ -40,13 +40,13 @@ assert(
);
```
`MyComponent` should render to the DOM.
`MyComponent` dovrebbe essere presentato nel DOM.
```js
assert(document.getElementById('challenge-node').childNodes.length === 1);
```
`MyComponent` should have a constructor calling `super` with `props`.
`MyComponent` dovrebbe avere un costruttore che chiama `super` con `props`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d4036177
title: Write a Simple Counter
title: Scrivere un semplice contatore
challengeType: 6
forumTopicId: 301425
dashedName: write-a-simple-counter
@ -8,17 +8,17 @@ dashedName: write-a-simple-counter
# --description--
You can design a more complex stateful component by combining the concepts covered so far. These include initializing `state`, writing methods that set `state`, and assigning click handlers to trigger these methods.
È possibile progettare un componente stateful più complesso combinando i concetti visti finora. Questi includono l'inizializzazione dello `state`, la scrittura di metodi che impostano lo `state` e l'assegnazione di gestori di click per attivare questi metodi.
# --instructions--
The `Counter` component keeps track of a `count` value in `state`. There are two buttons which call methods `increment()` and `decrement()`. Write these methods so the counter value is incremented or decremented by 1 when the appropriate button is clicked. Also, create a `reset()` method so when the reset button is clicked, the count is set to 0.
Il componente `Counter` tiene traccia di un valore `count` nello `state`. Ci sono due bottoni che chiamano i metodi `increment()` e `decrement()`. Scrivi questi metodi in modo che il valore del contatore venga incrementato o decrementato di 1 quando viene fatto click sul bottone appropriato. Inoltre, crea un metodo `reset()` in modo che quando si clicca il pulsante reset, il conteggio venga impostato a 0.
**Note:** Make sure you don't modify the `className`s of the buttons. Also, remember to add the necessary bindings for the newly-created methods in the constructor.
**Nota:** Assicurati di non modificare le `className` dei bottoni. Inoltre, ricordati di aggiungere i legami (bindings) necessari ai metodi appena creati nel costruttore.
# --hints--
`Counter` should return a `div` element which contains three buttons with text content in this order `Increment!`, `Decrement!`, `Reset`.
`Counter` dovrebbe restituire un elemento `div` che contiene tre pulsanti con contenuto di testo nell'ordine: `Increment!`, `Decrement!`, `Reset`.
```js
assert(
@ -33,14 +33,14 @@ assert(
);
```
The state of `Counter` should initialize with a `count` property set to `0`.
Lo stato di `Counter` dovrebbe essere inizializzato con una proprietà `count` impostata a `0`.
```js
const mockedComponent = Enzyme.mount(React.createElement(Counter));
assert(mockedComponent.find('h1').text() === 'Current Count: 0');
```
Clicking the increment button should increment the count by `1`.
Cliccando sul bottone di incremento il conteggio dovrebbe aumentare di `1`.
```js
const mockedComponent = Enzyme.mount(React.createElement(Counter));
@ -48,7 +48,7 @@ mockedComponent.find('.inc').simulate('click');
assert(mockedComponent.find('h1').text() === 'Current Count: 1');
```
Clicking the decrement button should decrement the count by `1`.
Cliccando sul bottone di decremento il conteggio dovrebbe diminuire di `1`.
```js
const mockedComponent = Enzyme.mount(React.createElement(Counter));
@ -56,7 +56,7 @@ mockedComponent.find('.dec').simulate('click');
assert(mockedComponent.find('h1').text() === 'Current Count: -1');
```
Clicking the reset button should reset the count to `0`.
Cliccando sul bottone di reset il conteggio dovrebbe essere reimpostato a `0`.
```js
const mockedComponent = Enzyme.mount(React.createElement(Counter));

View File

@ -1,6 +1,6 @@
---
id: 587d781b367417b2b2512abc
title: Adjust the background-color Property of Text
title: Ajustar a propriedade background-color (cor de fundo) de textos
challengeType: 0
videoUrl: 'https://scrimba.com/c/cEDqwA6'
forumTopicId: 301032
@ -9,23 +9,23 @@ dashedName: adjust-the-background-color-property-of-text
# --description--
Instead of adjusting your overall background or the color of the text to make the foreground easily readable, you can add a `background-color` to the element holding the text you want to emphasize. This challenge uses `rgba()` instead of `hex` codes or normal `rgb()`.
Em vez de ajustar o fundo geral ou a cor do texto para tornar o primeiro plano facilmente legível, você pode adicionar a propriedade `background-color` ao elemento que contém o texto que deseja enfatizar. Este desafio usa a função `rgba()` em vez de códigos `hex` ou `rgb()` normal.
<blockquote>rgba stands for:<br>  r = red<br>  g = green<br>  b = blue<br>  a = alpha/level of opacity</blockquote>
<blockquote>rgba significa:<br>r = red (vermelho)<br>g = green (verde)<br>b = blue (azul)<br> a = alpha (nível de opacidade)</blockquote>
The RGB values can range from 0 to 255. The alpha value can range from 1, which is fully opaque or a solid color, to 0, which is fully transparent or clear. `rgba()` is great to use in this case, as it allows you to adjust the opacity. This means you don't have to completely block out the background.
Os valores RGB podem variar de 0 a 255. O valor alpha (nível de transparência) pode variar de 1, que é totalmente opaco ou de cor sólida, a 0, que é totalmente transparente. Utilizar `rgba()` neste caso é ótimo, pois permite que você ajuste a opacidade. Isso significa que você não precisa eliminar completamente o fundo.
You'll use `background-color: rgba(45, 45, 45, 0.1)` for this challenge. It produces a dark gray color that is nearly transparent given the low opacity value of 0.1.
Você usará a propriedade `background-color: rgba(45, 45, 45, 0.1)` para este desafio. Estes valores produzem uma cor cinza escuro que é quase transparente devido ao baixo valor da opacidade - 0.1.
# --instructions--
To make the text stand out more, adjust the `background-color` of the `h4` element to the given `rgba()` value.
Para fazer o texto se destacar mais, ajuste a propriedade `background-color` do elemento `h4` para o valor `rgba()` fornecido anteriormente.
Also for the `h4`, remove the `height` property and add `padding` of 10px.
Também para o `h4`, remova a propriedade `height` e adicione `padding` de 10px.
# --hints--
Your code should add a `background-color` property to the `h4` element set to `rgba(45, 45, 45, 0.1)`.
O código deve adicionar uma propriedade `background-color` ao elemento `h4` com o valor de `rgba(45, 45, 45, 0.1)`.
```js
assert(
@ -35,7 +35,7 @@ assert(
);
```
Your code should add a `padding` property to the `h4` element and set it to 10 pixels.
O código deve adicionar uma propriedade `padding` ao elemento `h4` e configurá-lo para 10 pixels.
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
The `height` property on the `h4` element should be removed.
A propriedade `height` do elemento `h4` deve ser removida.
```js
assert(!($('h4').css('height') == '25px'));

View File

@ -1,6 +1,6 @@
---
id: 587d78a4367417b2b2512ad3
title: Adjust the Color of Various Elements to Complementary Colors
title: Ajustar a cor de vários elementos para cores complementares
challengeType: 0
videoUrl: 'https://scrimba.com/c/cWmPpud'
forumTopicId: 301033
@ -9,33 +9,33 @@ dashedName: adjust-the-color-of-various-elements-to-complementary-colors
# --description--
The Complementary Colors challenge showed that opposite colors on the color wheel can make each other appear more vibrant when placed side-by-side. However, the strong visual contrast can be jarring if it's overused on a website, and can sometimes make text harder to read if it's placed on a complementary-colored background. In practice, one of the colors is usually dominant and the complement is used to bring visual attention to certain content on the page.
O desafio das Cores Complementares mostrou que cores opostas no círculo cromático podem fazer as demais cores parecerem mais vibrantes quando colocadas lado a lado. No entanto, o forte contraste visual pode ser chocante se for usado demais em um site e, às vezes, pode tornar o texto mais difícil de ler se for colocado em um fundo de cores complementares. Na prática, uma das cores geralmente é dominante e o complemento é usado para chamar a atenção visual para determinado conteúdo da página.
# --instructions--
This page will use a shade of teal (`#09A7A1`) as the dominant color, and its orange (`#FF790E`) complement to visually highlight the sign-up buttons. Change the `background-color` of both the `header` and `footer` from black to the teal color. Then change the `h2` text `color` to teal as well. Finally, change the `background-color` of the `button` to the orange color.
Esta página usará um tom de azul-petróleo (`#09A7A1`) como cor dominante Seu complemento laranja (`#FF790E`) será usado para destacar visualmente os botões de inscrição. Altere a propriedade `background-color` do `header` e do `footer` de preto para azul-petróleo. Em seguida, altere a propriedade `color` do `h2` para azul-petróleo também. Finalmente, mude a propriedade `background-color` do `button` para a cor laranja.
# --hints--
The `header` element should have a `background-color` of #09A7A1.
O elemento `header` deve ter uma propriedade `background-color` com o valor de #09A7A1.
```js
assert($('header').css('background-color') == 'rgb(9, 167, 161)');
```
The `footer` element should have a `background-color` of #09A7A1.
O elemento `footer` deve ter uma propriedade `background-color` com o valor de #09A7A1.
```js
assert($('footer').css('background-color') == 'rgb(9, 167, 161)');
```
The `h2` element should have a `color` of #09A7A1.
O elemento `h2` deve ter uma propriedade `color` com o valor de #09A7A1.
```js
assert($('h2').css('color') == 'rgb(9, 167, 161)');
```
The `button` element should have a `background-color` of #FF790E.
O elemento `button` deve ter uma propriedade `background-color` com o valor de #FF790E.
```js
assert($('button').css('background-color') == 'rgb(255, 121, 14)');

View File

@ -1,6 +1,6 @@
---
id: 587d7791367417b2b2512ab5
title: Adjust the Height of an Element Using the height Property
title: Ajustar a altura de um elemento usando a propriedade height
challengeType: 0
videoUrl: 'https://scrimba.com/c/cEDaDTN'
forumTopicId: 301034
@ -9,7 +9,7 @@ dashedName: adjust-the-height-of-an-element-using-the-height-property
# --description--
You can specify the height of an element using the `height` property in CSS, similar to the `width` property. Here's an example that changes the height of an image to 20px:
Você pode especificar a altura de um elemento usando a propriedade `height` no CSS, semelhante à propriedade `width`. Aqui está um exemplo que muda a altura de uma imagem para 20px:
```css
img {
@ -19,13 +19,13 @@ img {
# --instructions--
Add a `height` property to the `h4` tag and set it to 25px.
Adicione a propriedade `height` à tag `h4` e defina-a com um valor de 25px.
**Note:** You may need to be at 100% zoom to pass the test on this challenge.
**Observação:** talvez você precise estar com 100% de zoom para passar no teste neste desafio.
# --hints--
Your code should change the `h4` `height` property to a value of 25 pixels.
O código deve alterar a propriedade `height` da tag `h4` para um valor de 25 pixels.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d781d367417b2b2512ac8
title: Adjust the Hover State of an Anchor Tag
title: Mudar o estilo de um link ao passar o mouse
challengeType: 0
videoUrl: 'https://scrimba.com/c/cakRGcm'
forumTopicId: 301035
@ -9,9 +9,9 @@ dashedName: adjust-the-hover-state-of-an-anchor-tag
# --description--
This challenge will touch on the usage of pseudo-classes. A pseudo-class is a keyword that can be added to selectors, in order to select a specific state of the element.
Este desafio abordará o uso de pseudo-classes. Uma pseudo-classe é uma palavra-chave que pode ser adicionada a seletores, a fim de selecionar um estado específico do elemento.
For example, the styling of an anchor tag can be changed for its hover state using the `:hover` pseudo-class selector. Here's the CSS to change the `color` of the anchor tag to red during its hover state:
Por exemplo, o estilo de um link pode ser alterado quando o cursor do mouse está sobre ele usando o seletor de pseudo-classe `:hover`. O código CSS para alterar a propriedade `color` de um link para vermelho quando o mouse está sobre ele é este:
```css
a:hover {
@ -21,17 +21,17 @@ a:hover {
# --instructions--
The code editor has a CSS rule to style all `a` tags black. Add a rule so that when the user hovers over the `a` tag, the `color` is blue.
O editor de código tem uma declaração de estilo CSS que estiliza todas as tags `a` com a cor preta. Adicione uma declaração de estilo para que, quando o usuário passar o mouse sobre a tag `a`, a propriedade `color` mude para azul.
# --hints--
The anchor tag `color` should remain black, only add CSS rules for the `:hover` state.
A propriedade `color` do link deve permanecer preta. A cor do texto deve mudar apenas no estado `:hover`.
```js
assert($('a').css('color') == 'rgb(0, 0, 0)');
```
The anchor tag should have a `color` of blue on hover.
O link deve ter a propriedade `color` de valor azul ao passar o mouse sobre ele.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d78a4367417b2b2512ad4
title: Adjust the Hue of a Color
title: Ajustar a tonalidade de uma cor
challengeType: 0
videoUrl: 'https://scrimba.com/c/cPp38TZ'
forumTopicId: 301036
@ -9,55 +9,55 @@ dashedName: adjust-the-hue-of-a-color
# --description--
Colors have several characteristics including hue, saturation, and lightness. CSS3 introduced the `hsl()` property as an alternative way to pick a color by directly stating these characteristics.
As cores têm várias características, incluindo tonalidade, saturação e luminosidade. CSS3 introduziu a função `hsl()` como uma forma alternativa de escolher uma cor informando diretamente essas características.
**Hue** is what people generally think of as 'color'. If you picture a spectrum of colors starting with red on the left, moving through green in the middle, and blue on right, the hue is where a color fits along this line. In `hsl()`, hue uses a color wheel concept instead of the spectrum, where the angle of the color on the circle is given as a value between 0 and 360.
**Tonalidade** é o que as pessoas geralmente chamam de 'cor'. Se você imaginar um espectro de cores começando com o vermelho à esquerda, passando pelo verde no meio e pelo azul à direita, a tonalidade é qualquer cor que esteja dentro deste espectro. No `hsl()`, a tonalidade é definida usando o conceito de círculo cromático em vez de um espectro, onde o ângulo da cor no círculo é um valor entre 0 e 360.
**Saturation** is the amount of gray in a color. A fully saturated color has no gray in it, and a minimally saturated color is almost completely gray. This is given as a percentage with 100% being fully saturated.
**Saturação** é a quantidade de cinza em uma cor. Uma cor totalmente saturada não contém cinza e uma cor minimamente saturada é quase totalmente cinza. Essa característica é definida usando porcentagem, onde 100% é totalmente saturado.
**Lightness** is the amount of white or black in a color. A percentage is given ranging from 0% (black) to 100% (white), where 50% is the normal color.
**Luminosidade** é a quantidade de branco ou preto em uma cor. Um valor válido, em porcentagem, varia de 0% (preto) a 100% (branco), onde 50% é a cor normal.
Here are a few examples of using `hsl()` with fully-saturated, normal lightness colors:
Aqui estão alguns exemplos de uso do `hsl()` com cores totalmente saturadas e luminosidade normal:
<table class='table table-striped'><thead><tr><th>Color</th><th>HSL</th></tr></thead><tbody><tr><td>red</td><td>hsl(0, 100%, 50%)</td></tr><tr><td>yellow</td><td>hsl(60, 100%, 50%)</td></tr><tr><td>green</td><td>hsl(120, 100%, 50%)</td></tr><tr><td>cyan</td><td>hsl(180, 100%, 50%)</td></tr><tr><td>blue</td><td>hsl(240, 100%, 50%)</td></tr><tr><td>magenta</td><td>hsl(300, 100%, 50%)</td></tr></tbody></table>
<table class='table table-striped'><thead><tr><th>Cor</th><th>HSL</th></tr></thead><tbody><tr><td>vermelho</td><td>hsl(0, 100%, 50%)</td></tr><tr><td>amarelo</td><td>hsl(60, 100%, 50%)</td></tr><tr><td>verde</td><td>hsl(120, 100%, 50%)</td></tr><tr><td>ciano</td><td>hsl(180, 100%, 50%)</td></tr><tr><td>azul</td><td>hsl(240, 100%, 50%)</td></tr><tr><td>magenta</td><td>hsl(300, 100%, 50%)</td></tr></tbody></table>
# --instructions--
Change the `background-color` of each `div` element based on the class names (`green`, `cyan`, or `blue`) using `hsl()`. All three should have full saturation and normal lightness.
Altere a propriedade `background-color` de cada elemento `div` com base nos nomes das classes (`green`, `cyan` ou `blue`) usando `hsl()`. Todos as três devem estar totalmente saturadas e ter luminosidade normal.
# --hints--
Your code should use the `hsl()` property to declare the color `green`.
Você deve usar a função `hsl()` para declarar a cor `green` (verde).
```js
assert(code.match(/\.green\s*?{\s*?background-color\s*:\s*?hsl/gi));
```
Your code should use the `hsl()` property to declare the color `cyan`.
Você deve usar a função `hsl()` para declarar a cor `cyan` (ciano).
```js
assert(code.match(/\.cyan\s*?{\s*?background-color\s*:\s*?hsl/gi));
```
Your code should use the `hsl()` property to declare the color `blue`.
Você deve usar a função `hsl()` para declarar a cor `blue` (blue).
```js
assert(code.match(/\.blue\s*?{\s*?background-color\s*:\s*?hsl/gi));
```
The `div` element with class `green` should have a `background-color` of green.
O elemento `div` com a classe `green` deve ter apropriedade `background-color` com o valor green (verde).
```js
assert($('.green').css('background-color') == 'rgb(0, 255, 0)');
```
The `div` element with class `cyan` should have a `background-color` of cyan.
O elemento `div` com a classe `cyan` deve ter apropriedade `background-color` com o valor cyan (ciano).
```js
assert($('.cyan').css('background-color') == 'rgb(0, 255, 255)');
```
The `div` element with class `blue` should have a `background-color` of blue.
O elemento `div` com a classe `blue` deve ter apropriedade `background-color` com o valor blue (azul).
```js
assert($('.blue').css('background-color') == 'rgb(0, 0, 255)');

View File

@ -1,6 +1,6 @@
---
id: 587d781b367417b2b2512abd
title: Adjust the Size of a Header Versus a Paragraph Tag
title: Contrastar o tamanho de um título com o de um parágrafo
challengeType: 0
videoUrl: 'https://scrimba.com/c/c3bRPTz'
forumTopicId: 301037
@ -9,15 +9,15 @@ dashedName: adjust-the-size-of-a-header-versus-a-paragraph-tag
# --description--
The font size of header tags (`h1` through `h6`) should generally be larger than the font size of paragraph tags. This makes it easier for the user to visually understand the layout and level of importance of everything on the page. You use the `font-size` property to adjust the size of the text in an element.
O tamanho da tipografia das tags de títulos (`h1` a `h6`) geralmente deve ser maior do que o tamanho da tipografia das tags de parágrafo. Isso torna mais fácil para o usuário entender visualmente o layout e o nível de importância de tudo na página. Você pode usar a propriedade `font-size` para ajustar o tamanho do texto de um elemento.
# --instructions--
To make the heading significantly larger than the paragraph, change the `font-size` of the `h4` tag to 27 pixels.
Para tornar o título significativamente maior do que o parágrafo, altere a propriedade `font-size` da tag `h4` para 27 pixels.
# --hints--
Your code should add a `font-size` property to the `h4` element set to 27 pixels.
Adicione ao elemento `h4` a propriedade `font-size` com o valor de 27 pixels.
```js
assert($('h4').css('font-size') == '27px');

View File

@ -1,6 +1,6 @@
---
id: 587d78a4367417b2b2512ad5
title: Adjust the Tone of a Color
title: Ajustar o tom de uma cor
challengeType: 0
videoUrl: 'https://scrimba.com/c/cEDJvT7'
forumTopicId: 301038
@ -9,15 +9,15 @@ dashedName: adjust-the-tone-of-a-color
# --description--
The `hsl()` option in CSS also makes it easy to adjust the tone of a color. Mixing white with a pure hue creates a tint of that color, and adding black will make a shade. Alternatively, a tone is produced by adding gray or by both tinting and shading. Recall that the 's' and 'l' of `hsl()` stand for saturation and lightness, respectively. The saturation percent changes the amount of gray and the lightness percent determines how much white or black is in the color. This is useful when you have a base hue you like, but need different variations of it.
A função `hsl()` no CSS também facilita o ajuste do tom de uma cor. A mistura de branco com uma tonalidade pura cria uma cor igual à cor que foi misturada com o branco e a adição de preto cria uma tonalidade mais escura. Como alternativa, um tom é produzido adicionando cinza ou matizando e sombreando. Lembre-se de que o 's' e 'l' de `hsl()` representam saturação e luminosidade, respectivamente. A porcentagem de saturação altera a quantidade de cinza e a porcentagem de luminosidade determina quanto de branco ou preto há na cor. Isso é útil quando você tem uma tonalidade básica de que gosta, mas precisa de diferentes variações.
# --instructions--
All elements have a default `background-color` of `transparent`. Our `nav` element currently appears to have a `cyan` background, because the element behind it has a `background-color` set to `cyan`. Add a `background-color` to the `nav` element so it uses the same `cyan` hue, but has `80%` saturation and `25%` lightness values to change its tone and shade.
Todos os elementos, por padrão, têm a propriedade `background-color` com o valor de `transparent`. O elemento `nav` atualmente parece ter um fundo `cyan`, porque o elemento por trás dele tem uma propriedade `background-color` definida com o valor `cyan`. Adicione a propriedade `background-color` ao elemento `nav` para que este elemento tenha a cor `cyan`, mas com saturação de `80%` e luminosidade de `25%` para alterar seu tom e sombreamento.
# --hints--
The `nav` element should have a `background-color` of the adjusted cyan tone using the `hsl()` property.
O elemento `nav` deve ter a propriedade `background-color` de tom ciano usando a função `hsl()`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7791367417b2b2512ab4
title: Adjust the Width of an Element Using the width Property
title: Ajustar a largura de um elemento usando a propriedade width
challengeType: 0
videoUrl: 'https://scrimba.com/c/cvVLPtN'
forumTopicId: 301039
@ -9,7 +9,7 @@ dashedName: adjust-the-width-of-an-element-using-the-width-property
# --description--
You can specify the width of an element using the `width` property in CSS. Values can be given in relative length units (such as `em`), absolute length units (such as `px`), or as a percentage of its containing parent element. Here's an example that changes the width of an image to 220px:
Você pode especificar a largura de um elemento usando a propriedade `width` no CSS. Os valores podem ser fornecidos em unidades de comprimento relativo (como `em`), unidades de comprimento absoluto (como `px`) ou como uma porcentagem do elemento pai que o contém. Aqui está um exemplo que altera a largura de uma imagem para 220px:
```css
img {
@ -19,11 +19,11 @@ img {
# --instructions--
Add a `width` property to the entire card and set it to an absolute value of 245px. Use the `fullCard` class to select the element.
Adicione a propriedade `width` com um valor absoluto de 245px ao cartão. Use a classe `fullCard` para selecionar o elemento.
# --hints--
Your code should change the `width` property of the card to 245 pixels by using the `fullCard` class selector.
Na classe `fullCard`, defina a propriedade `width` com um valor de 245 pixels.
```js
const fullCard = code.match(/\.fullCard\s*{[\s\S]+?[^}]}/g);

View File

@ -1,6 +1,6 @@
---
id: 587d78a8367417b2b2512ae5
title: Animate Elements at Variable Rates
title: Animar elementos em diferentes momentos
challengeType: 0
videoUrl: 'https://scrimba.com/c/cZ89WA4'
forumTopicId: 301040
@ -9,17 +9,17 @@ dashedName: animate-elements-at-variable-rates
# --description--
There are a variety of ways to alter the animation rates of similarly animated elements. So far, this has been achieved by applying an `animation-iteration-count` property and setting `@keyframes` rules.
Existem várias maneiras de alterar o momento de uma animação de um elemento. Até agora, isso foi realizado aplicando a propriedade `animation-iteration-count` e definindo regras `@keyframes`.
To illustrate, the animation on the right consists of two stars that each decrease in size and opacity at the 20% mark in the `@keyframes` rule, which creates the twinkle animation. You can change the `@keyframes` rule for one of the elements so the stars twinkle at different rates.
Para ilustrar, a animação à direita consiste em duas estrelas, cada uma diminuindo em tamanho e opacidade na marca de 20% na regra `@keyframes`. Você pode alterar a regra `@keyframes` em um dos elementos para que as estrelas cintilem em momentos diferentes.
# --instructions--
Alter the animation rate for the element with the class name of `star-1` by changing its `@keyframes` rule to 50%.
Altere o momento da animação do elemento que possui a classe `star-1` trocando a regra `@keyframes` para 50%.
# --hints--
The `@keyframes` rule for the `star-1` class should be 50%.
A regra `@keyframes` para a classe `star-1` deve ter o valor de 50%.
```js
assert(code.match(/twinkle-1\s*?{\s*?50%/g));

View File

@ -1,6 +1,6 @@
---
id: 587d78a8367417b2b2512ae3
title: Animate Elements Continually Using an Infinite Animation Count
title: Animar elementos infinitamente
challengeType: 0
videoUrl: 'https://scrimba.com/c/cVJDVfq'
forumTopicId: 301041
@ -9,21 +9,21 @@ dashedName: animate-elements-continually-using-an-infinite-animation-count
# --description--
The previous challenges covered how to use some of the animation properties and the `@keyframes` rule. Another animation property is the `animation-iteration-count`, which allows you to control how many times you would like to loop through the animation. Here's an example:
Os desafios anteriores cobriram como usar algumas das propriedades de animação e a regra `@keyframes`. Outra propriedade da animação é `animation-iteration-count`, que permite controlar quantas vezes você gostaria de repetir a animação. Um exemplo:
```css
animation-iteration-count: 3;
```
In this case the animation will stop after running 3 times, but it's possible to make the animation run continuously by setting that value to `infinite`.
Neste caso, a animação irá parar depois de repetir 3 vezes, mas é possível fazer a animação rodar infinitamente definindo esse valor para `infinite`.
# --instructions--
To keep the ball bouncing on the right on a continuous loop, change the `animation-iteration-count` property to `infinite`.
Para manter a bola quicando à direita em um loop contínuo, altere a propriedade `animation-iteration-count` para `infinite`.
# --hints--
The `animation-iteration-count` property should have a value of `infinite`.
A propriedade `animation-iteration-count` deve ter um valor de `infinite`.
```js
assert($('#ball').css('animation-iteration-count') == 'infinite');

View File

@ -1,6 +1,6 @@
---
id: 587d78a8367417b2b2512ae6
title: Animate Multiple Elements at Variable Rates
title: Animar múltiplos elementos em diferentes momentos
challengeType: 0
videoUrl: 'https://scrimba.com/c/cnpWZc9'
forumTopicId: 301042
@ -9,29 +9,29 @@ dashedName: animate-multiple-elements-at-variable-rates
# --description--
In the previous challenge, you changed the animation rates for two similarly animated elements by altering their `@keyframes` rules. You can achieve the same goal by manipulating the `animation-duration` of multiple elements.
No desafio anterior, você mudou o momento da animação de dois elementos com a mesma animação ao alterar a regra `@keyframes`. Você pode alcançar o mesmo resultado manipulando a propriedade `animation-duration` de vários elementos.
In the animation running in the code editor, there are three stars in the sky that twinkle at the same rate on a continuous loop. To make them twinkle at different rates, you can set the `animation-duration` property to different values for each element.
Na animação sendo executada no editor de código, há três estrelas no céu que cintilam ao mesmo instante infinitamente. Para fazê-las brilhar com ritmos diferentes, você pode definir a propriedade `animation-duration` com valores diferentes para cada elemento.
# --instructions--
Set the `animation-duration` of the elements with the classes `star-1`, `star-2`, and `star-3` to 1s, 0.9s, and 1.1s, respectively.
Defina a propriedade `animation-duration` dos elementos com as classes `star-1`, `star-2`, e `star-3` para 1s, 0.9s, e 1.1s, respectivamente.
# --hints--
The `animation-duration` property for the star with class `star-1` should remain at 1s.
O valor da propriedade `animation-duration` da estrela com a classe `star-1` deve permanecer em 1s.
```js
assert($('.star-1').css('animation-duration') == '1s');
```
The `animation-duration` property for the star with class `star-2` should be 0.9s.
O valor da propriedade `animation-duration` da estrela com a classe `star-2` deve ser 0.9s.
```js
assert($('.star-2').css('animation-duration') == '0.9s');
```
The `animation-duration` property for the star with class `star-3` should be 1.1s.
O valor da propriedade `animation-duration` da estrela com a classe `star-3` deve ser 1.1s.
```js
assert($('.star-3').css('animation-duration') == '1.1s');

View File

@ -1,6 +1,6 @@
---
id: 587d78a3367417b2b2512ad0
title: Center an Element Horizontally Using the margin Property
title: Centralizar um elemento horizontalmente usando a propriedade margin
challengeType: 0
videoUrl: 'https://scrimba.com/c/cyLJqU4'
forumTopicId: 301043
@ -9,17 +9,17 @@ dashedName: center-an-element-horizontally-using-the-margin-property
# --description--
Another positioning technique is to center a block element horizontally. One way to do this is to set its `margin` to a value of auto.
Outra técnica de posicionamento é centralizar um elemento de bloco horizontalmente. Uma maneira de fazer isso é definir a propriedade `margin` para o valor "auto".
This method works for images, too. Images are inline elements by default, but can be changed to block elements when you set the `display` property to `block`.
Esse método também funciona para imagens. Imagens são elementos inline por padrão, mas podem ser alterados para elementos de bloco caso você defina o valor da propriedade `display` para `block`.
# --instructions--
Center the `div` on the page by adding a `margin` property with a value of `auto`.
Centralize a `div` na página adicionando a propriedade `margin` com o valor `auto`.
# --hints--
The `div` should have a `margin` set to `auto`.
Esta `div` deve conter a propriedade `margin` definida com o valor `auto`.
```js
assert(code.match(/margin:\s*?auto;/g));

View File

@ -1,6 +1,6 @@
---
id: bad87fee1348bd9aedf08808
title: Specify How Fonts Should Degrade
title: O que fazer quando uma tipografia não estiver disponível
challengeType: 0
videoUrl: 'https://scrimba.com/c/cpVKBfQ'
forumTopicId: 18304
@ -9,11 +9,11 @@ dashedName: specify-how-fonts-should-degrade
# --description--
There are several default fonts that are available in all browsers. These generic font families include `monospace`, `serif` and `sans-serif`.
Por padrão, existem várias tipografias disponíveis em todos os navegadores. As tipografias padrão são: `monospace`, `serif` e `sans-serif`.
When one font isn't available, you can tell the browser to "degrade" to another font.
Quando uma tipografia não estiver disponível, você pode dizer ao navegador para usar outra tipografia.
For example, if you wanted an element to use the `Helvetica` font, but degrade to the `sans-serif` font when `Helvetica` isn't available, you will specify it as follows:
Por exemplo, se um elemento usa a tipografia `Helvetica`, mas você quer que ele use `sans-serif` quando a `Helvetica` não estiver disponível, você pode fazer assim:
```css
p {
@ -21,19 +21,19 @@ p {
}
```
Generic font family names are not case-sensitive. Also, they do not need quotes because they are CSS keywords.
O nome dessas tipografias não diferenciam maiúsculas de minúsculas. Além disso, eles não precisam de aspas porque são palavras-chave do CSS.
# --instructions--
To begin, apply the `monospace` font to the `h2` element, so that it now has two fonts - `Lobster` and `monospace`.
Para começar, aplique a tipografia `monospace` ao elemento `h2`, fazendo com que o elemento tenha duas tipografias - `Lobster` e `monospace`.
In the last challenge, you imported the `Lobster` font using the `link` tag. Now comment out that import of the `Lobster` font (using the HTML comments you learned before) from Google Fonts so that it isn't available anymore. Notice how your `h2` element degrades to the `monospace` font.
No desafio anterior, você importou a tipografia `Lobster` usando a tag `link`. Comente a importação da tipografia `Lobster` (usando os comentários HTML que você aprendeu antes) do Google Fonts para que ela não esteja mais disponível. Note como o elemento `h2` muda para a tipografia `monospace`.
**Note:** If you have the `Lobster` font installed on your computer, you won't see the degradation because your browser is able to find the font.
**Observação:** se você tiver a tipografia `Lobster` instalada em seu computador, não verá a mudança porque seu navegador é capaz de encontrá-la.
# --hints--
Your h2 element should use the font `Lobster`.
O elemento h2 deve usar a tipografia `Lobster`.
```js
assert(
@ -43,7 +43,7 @@ assert(
);
```
Your h2 element should degrade to the font `monospace` when `Lobster` is not available.
O elemento h2 deve mudar para a tipografia `monospace` quando `Lobster` não estiver disponível.
```js
assert(
@ -53,13 +53,13 @@ assert(
);
```
You should comment out your call to Google for the `Lobster` font by putting `<!--` in front of it.
Você deve comentar a importação da tipografia `Lobster` usando `<!--`.
```js
assert(new RegExp('<!--[^fc]', 'gi').test(code));
```
You should close your comment by adding `-->`.
Você deve fechar o comentário usando `-->`.
```js
assert(new RegExp('[^fc]-->', 'gi').test(code));
@ -141,9 +141,9 @@ assert(new RegExp('[^fc]-->', 'gi').test(code));
<h2 class="red-text">CatPhotoApp</h2>
<main>
<p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<div>
<p>Things cats love:</p>
<ul>
@ -158,7 +158,7 @@ assert(new RegExp('[^fc]-->', 'gi').test(code));
<li>other cats</li>
</ol>
</div>
<form action="https://freecatphotoapp.com/submit-cat-photo">
<label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>

View File

@ -1,6 +1,6 @@
---
id: bad87fee1348bd9aefe08806
title: Style Multiple Elements with a CSS Class
title: Estilizar vários elementos com apenas uma classe CSS
challengeType: 0
videoUrl: 'https://scrimba.com/c/cRkVbsQ'
forumTopicId: 18311
@ -9,29 +9,29 @@ dashedName: style-multiple-elements-with-a-css-class
# --description--
Classes allow you to use the same CSS styles on multiple HTML elements. You can see this by applying your `red-text` class to the first `p` element.
As classes permitem que você use os mesmos estilos CSS em diferentes elementos HTML. Você pode ver isso aplicando a classe `red-text` ao primeiro elemento `p`.
# --hints--
Your `h2` element should be red.
O elemento `h2` deve ser vermelho.
```js
assert($('h2').css('color') === 'rgb(255, 0, 0)');
```
Your `h2` element should have the class `red-text`.
O elemento `h2` deve ter a classe `red-text`.
```js
assert($('h2').hasClass('red-text'));
```
Your first `p` element should be red.
O primeiro elemento `p` deve ser vermelho.
```js
assert($('p:eq(0)').css('color') === 'rgb(255, 0, 0)');
```
Your second and third `p` elements should not be red.
O segundo e terceiro elementos `p` não devem ser vermelhos.
```js
assert(
@ -40,7 +40,7 @@ assert(
);
```
Your first `p` element should have the class `red-text`.
O primeiro elemento `p` deve ter a classe `red-text`.
```js
assert($('p:eq(0)').hasClass('red-text'));
@ -102,9 +102,9 @@ assert($('p:eq(0)').hasClass('red-text'));
<h2 class="red-text">CatPhotoApp</h2>
<main>
<p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<div>
<p>Things cats love:</p>
<ul>
@ -119,7 +119,7 @@ assert($('p:eq(0)').hasClass('red-text'));
<li>other cats</li>
</ol>
</div>
<form action="https://freecatphotoapp.com/submit-cat-photo">
<label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>

View File

@ -1,6 +1,6 @@
---
id: bad87fee1348bd9aedf08736
title: Style the HTML Body Element
title: Estilizar o elemento HTML body
challengeType: 0
videoUrl: 'https://scrimba.com/c/cB77PHW'
forumTopicId: 18313
@ -9,15 +9,15 @@ dashedName: style-the-html-body-element
# --description--
Now let's start fresh and talk about CSS inheritance.
Vamos começar do início e falar sobre o conceito de herança dentro do CSS.
Every HTML page has a `body` element.
Toda página HTML possui um elemento `body`.
# --instructions--
We can prove that the `body` element exists here by giving it a `background-color` of black.
Podemos provar que o elemento `body` existe aqui definindo a propriedade `background-color` com o valor black (preto).
We can do this by adding the following to our `style` element:
Para fazer isso, adicione ao elemento `style` o seguinte código:
```css
body {
@ -27,13 +27,13 @@ body {
# --hints--
Your `body` element should have the `background-color` of black.
O elemento `body` deve ter a propriedade `background-color` com o valor de preto (black).
```js
assert($('body').css('background-color') === 'rgb(0, 0, 0)');
```
Your CSS rule should be properly formatted with both opening and closing curly brackets.
O código CSS deve ser formatado corretamente, contendo chaves de abertura e fechamento.
```js
assert(
@ -41,7 +41,7 @@ assert(
);
```
Your CSS rule should end with a semi-colon.
A declaração do estilo CSS deve terminar com um ponto e vírgula.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: bad82fee1322bd9aedf08721
title: Understand Absolute versus Relative Units
title: Diferenças entre unidades absolutas e relativas
challengeType: 0
videoUrl: 'https://scrimba.com/c/cN66JSL'
forumTopicId: 301089
@ -9,21 +9,21 @@ dashedName: understand-absolute-versus-relative-units
# --description--
The last several challenges all set an element's margin or padding with pixels (`px`). Pixels are a type of length unit, which is what tells the browser how to size or space an item. In addition to `px`, CSS has a number of different length unit options that you can use.
Todos os últimos desafios definiram a margem ou preenchimento de um elemento usando pixels (`px`). Pixels são um tipo de unidade de comprimento, que informa ao navegador como dimensionar ou espaçar um item. Além do `px`, o CSS possui outras opções de unidades de comprimento que você pode usar.
The two main types of length units are absolute and relative. Absolute units tie to physical units of length. For example, `in` and `mm` refer to inches and millimeters, respectively. Absolute length units approximate the actual measurement on a screen, but there are some differences depending on a screen's resolution.
Os dois principais tipos de unidades de comprimento são: absoluto e relativo. As unidades absolutas estão vinculadas às unidades físicas de comprimento. Por exemplo, `in` e `mm` referem-se a polegadas e milímetros, respectivamente. As unidades de comprimento absoluto aproximam-se da medida real em uma tela, mas existem algumas diferenças dependendo da resolução da tela.
Relative units, such as `em` or `rem`, are relative to another length value. For example, `em` is based on the size of an element's font. If you use it to set the `font-size` property itself, it's relative to the parent's `font-size`.
Unidades relativas, como `em` ou `rem`, são relativas a outro valor de comprimento. Por exemplo, `em` é baseado no tamanho da tipografia de um elemento. Se você usá-la para definir o valor da propriedade `font-size`, esse valor será relativo a propriedade `font-size` do elemento pai.
**Note:** There are several relative unit options that are tied to the size of the viewport. They are covered in the Responsive Web Design Principles section.
**Observação:** existem diversas unidades do tipo relativo que são vinculadas ao tamanho da janela do navegador (viewport). Elas serão abordadas na seção Princípios de Web Design Responsivo.
# --instructions--
Add a `padding` property to the element with class `red-box` and set it to `1.5em`.
No elemento que possui a classe `red-box`, adicione a propriedade `padding` com o valor `1.5em`.
# --hints--
Your `red-box` class should have a `padding` property.
A classe `red-box` deve ter a propriedade `padding`.
```js
assert(
@ -34,7 +34,7 @@ assert(
);
```
Your `red-box` class should give elements 1.5em of `padding`.
A classe `red-box` deve dar aos elementos 1.5em de `padding`.
```js
assert(code.match(/\.red-box\s*?{[\s\S]*padding\s*:\s*?1\.5em/gi));

View File

@ -1,6 +1,6 @@
---
id: bad87fee1348bd9aecf08806
title: Use a CSS Class to Style an Element
title: Usar uma classe para definir o estilo de um elemento
challengeType: 0
videoUrl: 'https://scrimba.com/c/c2MvDtV'
forumTopicId: 18337
@ -9,9 +9,9 @@ dashedName: use-a-css-class-to-style-an-element
# --description--
Classes are reusable styles that can be added to HTML elements.
As classes são declarações de estilos que podem ser reutilizadas em elementos HTML.
Here's an example CSS class declaration:
Aqui está um exemplo de como criar uma classe CSS:
```html
<style>
@ -21,35 +21,35 @@ Here's an example CSS class declaration:
</style>
```
You can see that we've created a CSS class called `blue-text` within the `<style>` tag. You can apply a class to an HTML element like this: `<h2 class="blue-text">CatPhotoApp</h2>`. Note that in your CSS `style` element, class names start with a period. In your HTML elements' class attribute, the class name does not include the period.
Você pode ver que criamos uma classe CSS chamada `blue-text` dentro da tag `<style>`. Você pode aplicar uma classe a um elemento HTML da seguinte forma: `<h2 class="blue-text">CatPhotoApp</h2>`. Observe que no elemento `style` o nome da classe começa com um ponto. Já no atributo de classe do elemento HTML, o nome da classe não inclui o ponto.
# --instructions--
Inside your `style` element, change the `h2` selector to `.red-text` and update the color's value from `blue` to `red`.
Dentro do elemento `style`, altere o seletor `h2` para `.red-text` e atualize o valor da cor de `blue` para `red`.
Give your `h2` element the `class` attribute with a value of `red-text`.
Dê ao elemento `h2` o atributo `class` com o valor de `red-text`.
# --hints--
Your `h2` element should be red.
O elemento `h2` deve ser vermelho.
```js
assert($('h2').css('color') === 'rgb(255, 0, 0)');
```
Your `h2` element should have the class `red-text`.
O elemento `h2` deve ter a classe `red-text`.
```js
assert($('h2').hasClass('red-text'));
```
Your stylesheet should declare a `red-text` class and have its color set to `red`.
No código CSS, declare uma classe `red-text` e defina a cor como `red`.
```js
assert(code.match(/\.red-text\s*\{\s*color\s*:\s*red;?\s*\}/g));
```
You should not use inline style declarations like `style="color: red"` in your `h2` element.
Você não deve usar declarações de estilo inline como, por exemplo, `style="color: red"` no elemento `h2`.
```js
assert($('h2').attr('style') === undefined);
@ -111,9 +111,9 @@ assert($('h2').attr('style') === undefined);
<h2 class="red-text">CatPhotoApp</h2>
<main>
<p>Click here to view more <a href="#">cat photos</a>.</p>
<a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<div>
<p>Things cats love:</p>
<ul>
@ -128,7 +128,7 @@ assert($('h2').attr('style') === undefined);
<li>other cats</li>
</ol>
</div>
<form action="https://freecatphotoapp.com/submit-cat-photo">
<label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>

View File

@ -1,6 +1,6 @@
---
id: 5a9d727a424fe3d0e10cad12
title: Use a custom CSS Variable
title: Usar variáveis CSS
challengeType: 0
videoUrl: 'https://scrimba.com/c/cM989ck'
forumTopicId: 301090
@ -9,21 +9,21 @@ dashedName: use-a-custom-css-variable
# --description--
After you create your variable, you can assign its value to other CSS properties by referencing the name you gave it.
Depois de criar a variável, você pode atribuir o valor dela a outras propriedades CSS, referenciando o nome que você deu a ela.
```css
background: var(--penguin-skin);
```
This will change the background of whatever element you are targeting to gray because that is the value of the `--penguin-skin` variable. Note that styles will not be applied unless the variable names are an exact match.
O código acima mudará o fundo de qualquer elemento para cinza, porque esse é o valor da variável `--penguin-skin`. Tenha em mente que os estilos não serão aplicados a menos que o nome da variável que está sendo chamada seja igual ao nome da variável declarada.
# --instructions--
Apply the `--penguin-skin` variable to the `background` property of the `penguin-top`, `penguin-bottom`, `right-hand` and `left-hand` classes.
Aplique a variável `--penguin-skin` à propriedade `background` das classes `penguin-top`, `penguin-bottom`, `right-hand` e `left-hand`.
# --hints--
The `--penguin-skin` variable should be applied to the `background` property of the `penguin-top` class.
A variável `--penguin-skin` deve ser aplicada à propriedade `background` da classe `penguin-top`.
```js
assert(
@ -33,7 +33,7 @@ assert(
);
```
The `--penguin-skin` variable should be applied to the `background` property of the `penguin-bottom` class.
A variável `--penguin-skin` deve ser aplicada à propriedade `background` da classe `penguin-bottom`.
```js
assert(
@ -43,7 +43,7 @@ assert(
);
```
The `--penguin-skin` variable should be applied to the `background` property of the `right-hand` class.
A variável `--penguin-skin` deve ser aplicada à propriedade `background` da classe `right-hand`.
```js
assert(
@ -53,7 +53,7 @@ assert(
);
```
The `--penguin-skin` variable should be applied to the `background` property of the `left-hand` class.
A variável `--penguin-skin` deve ser aplicada à propriedade `background` da classe `left-hand`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5a9d72ad424fe3d0e10cad16
title: Use a media query to change a variable
title: Usar media queries para mudar o valor de uma variável
challengeType: 0
videoUrl: 'https://scrimba.com/c/cWmL8UP'
forumTopicId: 301091
@ -9,17 +9,17 @@ dashedName: use-a-media-query-to-change-a-variable
# --description--
CSS Variables can simplify the way you use media queries.
As variáveis CSS podem simplificar o modo como você usa media queries.
For instance, when your screen is smaller or larger than your media query break point, you can change the value of a variable, and it will apply its style wherever it is used.
Por exemplo, quando sua tela for menor ou maior do que o media query definido, você pode alterar o valor de uma variável e ela aplicará o estilo atribuído a ela onde quer que ela seja usada.
# --instructions--
In the `:root` selector of the `media query`, change it so `--penguin-size` is redefined and given a value of `200px`. Also, redefine `--penguin-skin` and give it a value of `black`. Then resize the preview to see this change in action.
Dentro da `media query` existe um seletor `:root`. Mude-o de forma que a variável `--penguin-size` seja redefinida e receba o valor de `200px`. Além disso, redefina a variável `--penguin-skin` e atribua a ela o valor `black`. Em seguida, redimensione a tela de visualização para ver a mudança.
# --hints--
`:root` should reassign the `--penguin-size` variable to `200px`.
`:root` deve reatribuir o valor da variável `--penguin-size` para `200px`.
```js
assert(
@ -29,7 +29,7 @@ assert(
);
```
`:root` should reassign the `--penguin-skin` variable to `black`.
`:root` deve reatribuir o valor da variável `--penguin-skin` para `black`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 58c383d33e2e3259241f3076
title: Use Attribute Selectors to Style Elements
title: Usar seletores de atributo para estilizar elementos
challengeType: 0
videoUrl: 'https://scrimba.com/c/cnpymfJ'
forumTopicId: 301092
@ -9,11 +9,11 @@ dashedName: use-attribute-selectors-to-style-elements
# --description--
You have been adding `id` or `class` attributes to elements that you wish to specifically style. These are known as ID and class selectors. There are other CSS Selectors you can use to select custom groups of elements to style.
Você tem adicionado atributos de `id` ou `class` aos elementos que você deseja especificamente estilizar. Eles são conhecidos como ID e seletores de classe. Existem outros seletores CSS que você pode usar para selecionar grupos de elementos para estilizar.
Let's bring out CatPhotoApp again to practice using CSS Selectors.
Vamos usar o CatPhotoApp novamente para praticar o uso de seletores CSS.
For this challenge, you will use the `[attr=value]` attribute selector to style the checkboxes in CatPhotoApp. This selector matches and styles elements with a specific attribute value. For example, the below code changes the margins of all elements with the attribute `type` and a corresponding value of `radio`:
Para este desafio, você usará o seletor de atributo `[attr=value]` para estilizar as caixas de seleção (checkboxes) no CatPhotoApp. Este seletor busca e estiliza elementos que possuam um atributo e valor específico. Por exemplo, o código abaixo altera as margens de todos os elementos com o atributo `type` que possua o valor `radio`:
```css
[type='radio'] {
@ -23,11 +23,11 @@ For this challenge, you will use the `[attr=value]` attribute selector to style
# --instructions--
Using the `type` attribute selector, try to give the checkboxes in CatPhotoApp a top margin of 10px and a bottom margin of 15px.
Selecione todo elemento que possua o atributo `type` e tente dar às caixas de seleção no CatPhotoApp uma margem superior de 10px e uma margem inferior de 15px.
# --hints--
The `type` attribute selector should be used to select the checkboxes.
Você deve selecionar as caixas de seleção (checkboxes) usando o seletor de atributo do tipo `type`.
```js
assert(
@ -37,7 +37,7 @@ assert(
);
```
The top margins of the checkboxes should be 10px.
As margens superiores das caixas de seleção devem ter 10px.
```js
assert(
@ -53,7 +53,7 @@ assert(
);
```
The bottom margins of the checkboxes should be 15px.
As margens inferiores das caixas de seleção devem ter 15px.
```js
assert(
@ -179,9 +179,9 @@ assert(
<h2 class="red-text">CatPhotoApp</h2>
<main>
<p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<a href="#"><img class="smaller-image thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<div class="silver-background">
<p>Things cats love:</p>
<ul>
@ -196,7 +196,7 @@ assert(
<li>other cats</li>
</ol>
</div>
<form action="https://freecatphotoapp.com/submit-cat-photo" id="cat-photo-form">
<label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>

View File

@ -1,6 +1,6 @@
---
id: bad87fee1348bd9afdf08726
title: Use Clockwise Notation to Specify the Margin of an Element
title: Usar a notação no sentido horário para especificar a margem de um elemento
challengeType: 0
videoUrl: 'https://scrimba.com/c/cnpybAd'
forumTopicId: 18345
@ -9,47 +9,47 @@ dashedName: use-clockwise-notation-to-specify-the-margin-of-an-element
# --description--
Let's try this again, but with `margin` this time.
Vamos tentar de novo, mas com `margin` desta vez.
Instead of specifying an element's `margin-top`, `margin-right`, `margin-bottom`, and `margin-left` properties individually, you can specify them all in one line, like this:
Em vez de especificar as propriedades `margin-top`, `margin-right`, `margin-bottom`, e `margin-left` individualmente, você pode especificá-las todas em uma linha, como esta:
```css
margin: 10px 20px 10px 20px;
```
These four values work like a clock: top, right, bottom, left, and will produce the exact same result as using the side-specific margin instructions.
Esses quatro valores funcionam como em um relógio: acima, à direita, abaixo, à esquerda. Eles produzirão exatamente o mesmo resultado como quando usamos as propriedades específicas para cada margem.
# --instructions--
Use Clockwise Notation to give the element with the `blue-box` class a margin of `40px` on its top and left side, but only `20px` on its bottom and right side.
Use a notação no sentido horário para dar ao elemento com a classe `blue-box` uma margem de `40px` nos lados superior e esquerdo, mas apenas `20px` nos lados inferior e direito.
# --hints--
Your `blue-box` class should give the top of elements `40px` of `margin`.
A classe `blue-box` deve dar aos elementos uma margem (`margin`) superior de `40px`.
```js
assert($('.blue-box').css('margin-top') === '40px');
```
Your `blue-box` class should give the right of elements `20px` of `margin`.
A classe `blue-box` deve dar aos elementos uma margem (`margin`) à direita de `20px`.
```js
assert($('.blue-box').css('margin-right') === '20px');
```
Your `blue-box` class should give the bottom of elements `20px` of `margin`.
A classe `blue-box` deve dar aos elementos uma margem (`margin`) inferior de `20px`.
```js
assert($('.blue-box').css('margin-bottom') === '20px');
```
Your `blue-box` class should give the left of elements `40px` of `margin`.
A classe `blue-box` deve dar aos elementos uma margem (`margin`) à esquerda de `40px`.
```js
assert($('.blue-box').css('margin-left') === '40px');
```
You should use the clockwise notation to set the margin of `blue-box` class.
Você deve usar a notação no sentido horário para definir a margem da classe `blue-box`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: bad87fee1348bd9aedf08826
title: Use Clockwise Notation to Specify the Padding of an Element
title: Usar a notação de sentido horário para especificar o preenchimento (padding) de um elemento
challengeType: 0
videoUrl: 'https://scrimba.com/c/cB7mBS9'
forumTopicId: 18346
@ -9,45 +9,45 @@ dashedName: use-clockwise-notation-to-specify-the-padding-of-an-element
# --description--
Instead of specifying an element's `padding-top`, `padding-right`, `padding-bottom`, and `padding-left` properties individually, you can specify them all in one line, like this:
Em vez de especificar as propriedades `padding-top`, `padding-right`, `padding-bottom` e `padding-left` individualmente, você pode especificar todas elas em uma única linha, assim:
```css
padding: 10px 20px 10px 20px;
```
These four values work like a clock: top, right, bottom, left, and will produce the exact same result as using the side-specific padding instructions.
Esses quatro valores funcionam como em um relógio: acima, à direita, abaixo, à esquerda. Eles produzirão exatamente o mesmo resultado como quando usamos as propriedades específicas para cada preenchimento.
# --instructions--
Use Clockwise Notation to give the `.blue-box` class a `padding` of `40px` on its top and left side, but only `20px` on its bottom and right side.
Use a notação no sentido horário para dar à classe `.blue-box` um preenchimento (`padding`) de `40px` nos lados superior e esquerdo, mas apenas `20px` nos lados inferior e direito.
# --hints--
Your `blue-box` class should give the top of elements `40px` of `padding`.
A classe `blue-box` deve dar `40px` de preenchimento (`padding`) no lado superior dos elementos.
```js
assert($('.blue-box').css('padding-top') === '40px');
```
Your `blue-box` class should give the right of elements `20px` of `padding`.
A classe `blue-box` deve dar `20px` de preenchimento (`padding`) no lado direito dos elementos.
```js
assert($('.blue-box').css('padding-right') === '20px');
```
Your `blue-box` class should give the bottom of elements `20px` of `padding`.
A classe `blue-box` deve dar `20px` de preenchimento (`padding`) no lado inferior dos elementos.
```js
assert($('.blue-box').css('padding-bottom') === '20px');
```
Your `blue-box` class should give the left of elements `40px` of `padding`.
A classe `blue-box` deve dar `40px` de preenchimento (`padding`) no lado esquerdo dos elementos.
```js
assert($('.blue-box').css('padding-left') === '40px');
```
You should use the clockwise notation to set the padding of `blue-box` class.
Você deve usar a notação no sentido horário para definir o padding dos elementos da classe `blue-box`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5a9d725e424fe3d0e10cad10
title: Use CSS Variables to change several elements at once
title: Usar variáveis CSS para alterar vários elementos de uma só vez
challengeType: 0
videoUrl: 'https://scrimba.com/c/c6bDECm'
forumTopicId: 301093
@ -9,17 +9,17 @@ dashedName: use-css-variables-to-change-several-elements-at-once
# --description--
<dfn>CSS Variables</dfn> are a powerful way to change many CSS style properties at once by changing only one value.
As <dfn>variáveis CSS</dfn> são uma maneira poderosa de alterar várias propriedades no CSS ao mesmo tempo alterando apenas um valor.
Follow the instructions below to see how changing just three values can change the styling of many elements.
Siga as instruções abaixo para ver como a alteração de apenas três valores podem alterar o estilo de muitos elementos.
# --instructions--
In the `penguin` class, change the `black` value to `gray`, the `gray` value to `white`, and the `yellow` value to `orange`.
Na classe `penguin`, altere o valor `black` para `gray`, o valor `gray` para `white` e o valor `yellow` para `orange`.
# --hints--
`penguin` class should declare the `--penguin-skin` variable and assign it to `gray`.
A classe `penguin` deve declarar a variável `--penguin-skin` e atribuí-la ao valor `gray`.
```js
assert(
@ -27,7 +27,7 @@ assert(
);
```
`penguin` class should declare the `--penguin-belly` variable and assign it to `white`.
A classe `penguin` deve declarar a variável `--penguin-belly` e atribuí-la ao valor `white`.
```js
assert(
@ -35,7 +35,7 @@ assert(
);
```
`penguin` class should declare the `--penguin-beak` variable and assign it to `orange`.
A classe `penguin` deve declarar a variável `--penguin-beak` e atribuí-la ao valor `orange`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: bad87fee1348bd9aedf08721
title: Use Hex Code to Mix Colors
title: Usar código hexadecimal para misturar cores
challengeType: 0
videoUrl: 'https://scrimba.com/c/cK89PhP'
forumTopicId: 18359
@ -9,67 +9,67 @@ dashedName: use-hex-code-to-mix-colors
# --description--
To review, hex codes use 6 hexadecimal digits to represent colors, two each for red (R), green (G), and blue (B) components.
Para revisar, os códigos hexadecimais usam 6 dígitos hexadecimais para representar as cores, dois para cada componente vermelho (R), verde (G) e azul (B).
From these three pure colors (red, green, and blue), we can vary the amounts of each to create over 16 million other colors!
A partir dessas três cores puras (vermelho, verde e azul), podemos variar as quantidades de cada uma para criar mais de 16 milhões de outras cores!
For example, orange is pure red, mixed with some green, and no blue. In hex code, this translates to being `#FFA500`.
Por exemplo, laranja é vermelho puro, misturado com um pouco de verde e sem azul. Em código hexadecimal, essa cor se traduz em `#FFA500`.
The digit `0` is the lowest number in hex code, and represents a complete absence of color.
O dígito `0` é o número mais baixo em código hexadecimal e representa uma ausência completa de cor.
The digit `F` is the highest number in hex code, and represents the maximum possible brightness.
O dígito `F` é o número mais alto em código hexadecimal e representa o brilho máximo possível.
# --instructions--
Replace the color words in our `style` element with their correct hex codes.
Substitua as palavras que representam cores no elemento `style` por seus códigos hexadecimais corretos.
<table class='table table-striped'><tbody><tr><th>Color</th><th>Hex Code</th></tr><tr><td>Dodger Blue</td><td><code>#1E90FF</code></td></tr><tr><td>Green</td><td><code>#00FF00</code></td></tr><tr><td>Orange</td><td><code>#FFA500</code></td></tr><tr><td>Red</td><td><code>#FF0000</code></td></tr></tbody></table>
<table class='table table-striped'><tbody><tr><th>Cor</th><th>Código hexadecimal</th></tr><tr><td>Azul dodger</td><td><code>#1E90FF</code></td></tr><tr><td>Verde</td><td><code>#00FF00</code></td></tr><tr><td>Laranja</td><td><code>#FFA500</code></td></tr><tr><td>Vermelho</td><td><code>#FF0000</code></td></tr></tbody></table>
# --hints--
Your `h1` element with the text `I am red!` should be given the `color` red.
O elemento `h1` com o texto `I am red!` deve receber a propriedade `color` com um valor de vermelho.
```js
assert($('.red-text').css('color') === 'rgb(255, 0, 0)');
```
The `hex code` for the color red should be used instead of the word `red`.
O código hexadecimal (`hex code`) para a cor vermelha deve ser usado em vez da palavra `red`.
```js
assert(code.match(/\.red-text\s*?{\s*?color\s*:\s*?(#FF0000|#F00)\s*?;?\s*?}/gi));
```
Your `h1` element with the text `I am green!` should be given the `color` green.
O elemento `h1` com o texto `I am green!` deve receber a propriedade `color` com um valor de verde.
```js
assert($('.green-text').css('color') === 'rgb(0, 255, 0)');
```
The `hex code` for the color green should be used instead of the word `green`.
O código hexadecimal (`hex code`) para a cor verde deve ser usado em vez da palavra `green`.
```js
assert(code.match(/\.green-text\s*?{\s*?color\s*:\s*?(#00FF00|#0F0)\s*?;?\s*?}/gi));
```
Your `h1` element with the text `I am dodger blue!` should be given the `color` dodger blue.
O elemento `h1` com o texto `I am dodger blue!` deve receber a propriedade `color` com um valor de azul dodger.
```js
assert($('.dodger-blue-text').css('color') === 'rgb(30, 144, 255)');
```
The `hex code` for the color dodger blue should be used instead of the word `dodgerblue`.
O código hexadecimal (`hex code`) para a cor azul dodger deve ser usado em vez da palavra `dodgerblue`.
```js
assert(code.match(/\.dodger-blue-text\s*?{\s*?color\s*:\s*?#1E90FF\s*?;?\s*?}/gi));
```
Your `h1` element with the text `I am orange!` should be given the `color` orange.
O elemento `h1` com o texto `I am orange!` deve receber a propriedade `color` com um valor de laranja.
```js
assert($('.orange-text').css('color') === 'rgb(255, 165, 0)');
```
The `hex code` for the color orange should be used instead of the word `orange`.
O código hexadecimal (`hex code`) para a cor laranja deve ser usado em vez da palavra `orange`.
```js
assert(code.match(/\.orange-text\s*?{\s*?color\s*:\s*?#FFA500\s*?;?\s*?}/gi));

View File

@ -1,6 +1,6 @@
---
id: bad87fee1348bd9aede08718
title: Use RGB values to Color Elements
title: Usar valores RGB para colorir elementos
challengeType: 0
videoUrl: 'https://scrimba.com/c/cRkp2fr'
forumTopicId: 18369
@ -9,25 +9,25 @@ dashedName: use-rgb-values-to-color-elements
# --description--
Another way you can represent colors in CSS is by using `RGB` values.
Outra maneira de representar cores em CSS é usando valores `RGB`.
The `RGB` value for black looks like this:
O valor `RGB` para cor preta é assim:
```css
rgb(0, 0, 0)
```
The `RGB` value for white looks like this:
O valor `RGB` para cor branca é assim:
```css
rgb(255, 255, 255)
```
Instead of using six hexadecimal digits like you do with hex code, with `RGB` you specify the brightness of each color with a number between 0 and 255.
Em vez de usar seis dígitos hexadecimais como você usa com código hexadecimal com `RGB`, você especifica o brilho de cada cor com um número entre 0 e 255.
If you do the math, the two digits for one color equal 16 times 16, which gives us 256 total values. So `RGB`, which starts counting from zero, has the exact same number of possible values as hex code.
Se fizer as contas, os dois dígitos para uma cor são iguais a 16 vezes 16, o que nos dá um total de 256 valores. Então, `RGB`, que começa a contar de zero, tem exatamente o mesmo número de valores possíveis que o código hexadecimal.
Here's an example of how you'd change the `body` background to orange using its RGB code.
Aqui está um exemplo de como você alteraria o fundo da `body` para laranja usando código RGB.
```css
body {
@ -37,17 +37,17 @@ body {
# --instructions--
Let's replace the hex code in our `body` element's background color with the RGB value for black: `rgb(0, 0, 0)`
Vamos substituir o código hexadecimal na cor de fundo do elemento `body` pelo valor RGB de preto: `rgb(0, 0, 0)`
# --hints--
Your `body` element should have a black background.
O elemento `body` deve ter um fundo preto.
```js
assert($('body').css('background-color') === 'rgb(0, 0, 0)');
```
You should use `rgb` to give your `body` element a background of black.
Você deve usar `rgb` para dar ao elemento `body` um fundo preto.
```js
assert(code.match(/rgb\s*\(\s*0\s*,\s*0\s*,\s*0\s*\)/gi));