chore(i18n,curriculum): processed translations (#42897)
This commit is contained in:
@ -101,19 +101,11 @@ assert(
|
||||
`handleSubmit` 應該調用 `event.preventDefault`。
|
||||
|
||||
```js
|
||||
const handleSubmit = MyForm.prototype.handleSubmit.toString();
|
||||
const allMatches = handleSubmit.match(/\bevent\.preventDefault\(\s*?\)/g) ?? [];
|
||||
const blockCommented = handleSubmit.match(
|
||||
/\/\*.*?\bevent\.preventDefault\(\s*?\).*?\*\//gs
|
||||
);
|
||||
const lineCommented = handleSubmit.match(
|
||||
/\/\/.*?\bevent\.preventDefault\(\s*?\)/g
|
||||
);
|
||||
const commentedMatches = [...(blockCommented ?? []), ...(lineCommented ?? [])];
|
||||
|
||||
assert(
|
||||
// At least one event.preventDefault() call exists and is not commented out
|
||||
allMatches.length > commentedMatches.length
|
||||
__helpers.isCalledWithNoArgs(
|
||||
'event.preventDefault',
|
||||
MyForm.prototype.handleSubmit.toString()
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
|
@ -101,19 +101,11 @@ assert(
|
||||
`handleSubmit` 应该调用 `event.preventDefault`。
|
||||
|
||||
```js
|
||||
const handleSubmit = MyForm.prototype.handleSubmit.toString();
|
||||
const allMatches = handleSubmit.match(/\bevent\.preventDefault\(\s*?\)/g) ?? [];
|
||||
const blockCommented = handleSubmit.match(
|
||||
/\/\*.*?\bevent\.preventDefault\(\s*?\).*?\*\//gs
|
||||
);
|
||||
const lineCommented = handleSubmit.match(
|
||||
/\/\/.*?\bevent\.preventDefault\(\s*?\)/g
|
||||
);
|
||||
const commentedMatches = [...(blockCommented ?? []), ...(lineCommented ?? [])];
|
||||
|
||||
assert(
|
||||
// At least one event.preventDefault() call exists and is not commented out
|
||||
allMatches.length > commentedMatches.length
|
||||
__helpers.isCalledWithNoArgs(
|
||||
'event.preventDefault',
|
||||
MyForm.prototype.handleSubmit.toString()
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
|
@ -101,19 +101,11 @@ El envío del formulario debe ejecutar `handleSubmit`, el cual debe establecer l
|
||||
`handleSubmit` debe llamar a `event.preventDefault`
|
||||
|
||||
```js
|
||||
const handleSubmit = MyForm.prototype.handleSubmit.toString();
|
||||
const allMatches = handleSubmit.match(/\bevent\.preventDefault\(\s*?\)/g) ?? [];
|
||||
const blockCommented = handleSubmit.match(
|
||||
/\/\*.*?\bevent\.preventDefault\(\s*?\).*?\*\//gs
|
||||
);
|
||||
const lineCommented = handleSubmit.match(
|
||||
/\/\/.*?\bevent\.preventDefault\(\s*?\)/g
|
||||
);
|
||||
const commentedMatches = [...(blockCommented ?? []), ...(lineCommented ?? [])];
|
||||
|
||||
assert(
|
||||
// At least one event.preventDefault() call exists and is not commented out
|
||||
allMatches.length > commentedMatches.length
|
||||
__helpers.isCalledWithNoArgs(
|
||||
'event.preventDefault',
|
||||
MyForm.prototype.handleSubmit.toString()
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
|
@ -101,19 +101,11 @@ L'invio del modulo dovrebbe eseguire `handleSubmit` che dovrebbe impostare la pr
|
||||
`handleSubmit` dovrebbe chiamare `event.preventDefault`
|
||||
|
||||
```js
|
||||
const handleSubmit = MyForm.prototype.handleSubmit.toString();
|
||||
const allMatches = handleSubmit.match(/\bevent\.preventDefault\(\s*?\)/g) ?? [];
|
||||
const blockCommented = handleSubmit.match(
|
||||
/\/\*.*?\bevent\.preventDefault\(\s*?\).*?\*\//gs
|
||||
);
|
||||
const lineCommented = handleSubmit.match(
|
||||
/\/\/.*?\bevent\.preventDefault\(\s*?\)/g
|
||||
);
|
||||
const commentedMatches = [...(blockCommented ?? []), ...(lineCommented ?? [])];
|
||||
|
||||
assert(
|
||||
// At least one event.preventDefault() call exists and is not commented out
|
||||
allMatches.length > commentedMatches.length
|
||||
__helpers.isCalledWithNoArgs(
|
||||
'event.preventDefault',
|
||||
MyForm.prototype.handleSubmit.toString()
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589a69f5f9fc0f352b528e71
|
||||
title: Implementation of Social Authentication II
|
||||
title: Implementazione dell'autenticazione con i social II
|
||||
challengeType: 2
|
||||
forumTopicId: 301557
|
||||
dashedName: implementation-of-social-authentication-ii
|
||||
@ -8,11 +8,11 @@ dashedName: implementation-of-social-authentication-ii
|
||||
|
||||
# --description--
|
||||
|
||||
The last part of setting up your GitHub authentication is to create the strategy itself. For this, you will need to add the dependency of `passport-github@~1.1.0` to your project and require it in your `auth.js` as `GithubStrategy` like this: `const GitHubStrategy = require('passport-github').Strategy;`. Do not forget to require and configure `dotenv` to use your environment variables.
|
||||
L'ultima parte della configurazione dell'autenticazione con GitHub è creare la strategia stessa. Per questo, è necessario aggiungere la dipendenza di `passport-github@~1.1.0` al tuo progetto e richiederlo nel tuo `auth.js` come `GithubStrategy` così: `const GitHubStrategy = require('passport-github').Strategy;`. Non dimenticare di richiedere e configurare `dotenv` per utilizzare le variabili d'ambiente.
|
||||
|
||||
To set up the GitHub strategy, you have to tell Passport to use an instantiated `GitHubStrategy`, which accepts 2 arguments: an object (containing `clientID`, `clientSecret`, and `callbackURL`) and a function to be called when a user is successfully authenticated, which will determine if the user is new and what fields to save initially in the user's database object. This is common across many strategies, but some may require more information as outlined in that specific strategy's GitHub README. For example, Google requires a *scope* as well which determines what kind of information your request is asking to be returned and asks the user to approve such access. The current strategy we are implementing has its usage outlined [here](https://github.com/jaredhanson/passport-github/), but we're going through it all right here on freeCodeCamp!
|
||||
Per impostare la strategia GitHub, devi dire al Passport di utilizzare un `GitHubStrategy` istantanziato, che accetta 2 argomenti: un oggetto (contenente `clientID`, `clientSecret`, e `callbackURL`) e una funzione da chiamare quando un utente viene autenticato con successo, che determinerà se l'utente è nuovo e quali campi salvare inizialmente nell'oggetto database dell'utente. Questo è comune in molte strategie, ma alcune possono richiedere ulteriori informazioni, come indicato nel README di quella specifica strategia GitHub. Ad esempio, Google richiede anche un *ambito* che determina il tipo di informazioni che la tua richiesta sta chiedendo di ricevere e chiede all'utente di approvare tale accesso. L'attuale strategia che stiamo implementando ha il suo utilizzo delineato [qui](https://github.com/jaredhanson/passport-github/), ma stiamo esaminando tutto qui su freeCodeCamp!
|
||||
|
||||
Here's how your new strategy should look at this point:
|
||||
Ecco come la tua nuova strategia dovrebbe essere a questo punto:
|
||||
|
||||
```js
|
||||
passport.use(new GitHubStrategy({
|
||||
@ -27,13 +27,13 @@ passport.use(new GitHubStrategy({
|
||||
));
|
||||
```
|
||||
|
||||
Your authentication won't be successful yet, and it will actually throw an error without the database logic and callback, but it should log your GitHub profile to your console if you try it!
|
||||
La tua autenticazione non avrà ancora successo, anzi lancerà un errore senza la logica del database e la chiamata, ma se provi dovrebbe registrare il tuo profilo GitHub sulla tua console!
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/ff3a1166684c1b184709ac0bee30dee6).
|
||||
Invia la tua pagina quando pensi di averlo fatto correttamente. Se dovessi incontrare degli errori, puoi controllare il progetto completato fino a questo punto [qui](https://gist.github.com/camperbot/ff3a1166684c1b184709ac0bee30dee6).
|
||||
|
||||
# --hints--
|
||||
|
||||
passport-github dependency should be added.
|
||||
passport-github deve essere aggiunto come dipendenza.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -52,7 +52,7 @@ passport-github dependency should be added.
|
||||
);
|
||||
```
|
||||
|
||||
passport-github should be required.
|
||||
passaporto-github deve essere richiesto.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -70,7 +70,7 @@ passport-github should be required.
|
||||
);
|
||||
```
|
||||
|
||||
GitHub strategy should be setup correctly thus far.
|
||||
La strategia di GitHub dovrebbe essere impostata correttamente finora.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589a69f5f9fc0f352b528e70
|
||||
title: Implementation of Social Authentication
|
||||
title: Implementazione dell'autenticazione con i social
|
||||
challengeType: 2
|
||||
forumTopicId: 301559
|
||||
dashedName: implementation-of-social-authentication
|
||||
@ -8,21 +8,21 @@ dashedName: implementation-of-social-authentication
|
||||
|
||||
# --description--
|
||||
|
||||
The basic path this kind of authentication will follow in your app is:
|
||||
Il percorso di base che seguirà questo tipo di autenticazione nella tua app è:
|
||||
|
||||
1. User clicks a button or link sending them to our route to authenticate using a specific strategy (e.g. GitHub).
|
||||
2. Your route calls `passport.authenticate('github')` which redirects them to GitHub.
|
||||
3. The page the user lands on, on GitHub, allows them to login if they aren't already. It then asks them to approve access to their profile from our app.
|
||||
4. The user is then returned to our app at a specific callback url with their profile if they are approved.
|
||||
5. They are now authenticated, and your app should check if it is a returning profile, or save it in your database if it is not.
|
||||
1. L'utente fa clic su un pulsante o link che li reindirizza alla nostra rotta per autenticarsi utilizzando una strategia specifica (ad esempio GitHub).
|
||||
2. La tua rotta chiama `passport.authenticate('github')` che li reindirizza a GitHub.
|
||||
3. La pagina su cui l'utente atterra, su GitHub, permette loro di effettuare il login se non sono già loggati. Poi chiede loro di approvare l'accesso al loro profilo dalla nostra app.
|
||||
4. L'utente viene quindi rimandato alla nostra app a una specifica url di callback con il loro profilo, se è approvato.
|
||||
5. Ora è autenticato, e la tua app dovrebbe controllare se si tratta di un profilo che è tornato, o salvarlo nel tuo database se non lo è.
|
||||
|
||||
Strategies with OAuth require you to have at least a *Client ID* and a *Client Secret* which is a way for the service to verify who the authentication request is coming from and if it is valid. These are obtained from the site you are trying to implement authentication with, such as GitHub, and are unique to your app--**THEY ARE NOT TO BE SHARED** and should never be uploaded to a public repository or written directly in your code. A common practice is to put them in your `.env` file and reference them like so: `process.env.GITHUB_CLIENT_ID`. For this challenge we're going to use the GitHub strategy.
|
||||
Le strategie con OAuth richiedono di avere almeno un *ID client* e un *Client Secret* che è un modo per il servizio di verificare da chi proviene la richiesta di autenticazione e se è valida. Questi sono ottenuti dal sito con cui si sta tentando di implementare l'autenticazione, ad esempio GitHub, e sono unici per la tua app--**NON DEVONO ESSERE CONDIVISI** e non dovrebbero mai essere caricati in un archivio pubblico o scritti direttamente nel tuo codice. Una pratica comune è metterli nel tuo file `.env` e fare riferimento a loro in questo modo: `process.env.GITHUB_CLIENT_ID`. Per questa sfida useremo la strategia GitHub.
|
||||
|
||||
Obtaining your *Client ID and Secret* from GitHub is done in your account profile settings under 'developer settings', then '[OAuth applications](https://github.com/settings/developers)'. Click 'Register a new application', name your app, paste in the url to your Replit homepage (**Not the project code's url**), and lastly, for the callback url, paste in the same url as the homepage but with `/auth/github/callback` added on. This is where users will be redirected for us to handle after authenticating on GitHub. Save the returned information as `'GITHUB_CLIENT_ID'` and `'GITHUB_CLIENT_SECRET'` in your `.env` file.
|
||||
L'ottenimento del tuo *Client ID e Client Secret* da GitHub viene effettuato nelle impostazioni del profilo del tuo account in 'developer settings', quindi in '[OAuth applications](https://github.com/settings/developers)'. Clicca su 'Register a new application', dai un nome alla tua app, incolla l'url alla tua homepage di Replit (**Non l'url del progetto**), e infine, per l'url di callback, incolla lo stesso url della homepage ma con l'aggiunta di `/auth/github/callback`. È qui che gli utenti verranno reindirizzati per essere gestiti da noi dopo l'autenticazione su GitHub. Salva le informazioni restituite come `'GITHUB_CLIENT_ID'` e `'GITHUB_CLIENT_SECRET'` nel tuo file `.env`.
|
||||
|
||||
In your `routes.js` file, add `showSocialAuth: true` to the homepage route, after `showRegistration: true`. Now, create 2 routes accepting GET requests: `/auth/github` and `/auth/github/callback`. The first should only call passport to authenticate `'github'`. The second should call passport to authenticate `'github'` with a failure redirect to `/`, and then if that is successful redirect to `/profile` (similar to our last project).
|
||||
Nel tuo file `routes.js`, aggiungi `showSocialAuth: true` alla rotta homepage, dopo `showRegistration: true`. Ora, crea 2 rotte che accettano le richieste GET: `/auth/github` e `/auth/github/callback`. La prima dovrebbe chiamare solo passport per autenticare `'github'`. La seconda dovrebbe chiamare passport per autenticare `'github'` con un reindirizzamento fallito a `/`, e poi, se questo è riuscito, reindirizzare a `/profile` (simile al nostro ultimo progetto).
|
||||
|
||||
An example of how `/auth/github/callback` should look is similar to how we handled a normal login:
|
||||
Un esempio di come `/auth/github/callback` deve essere è simile a come abbiamo gestito un normale login:
|
||||
|
||||
```js
|
||||
app.route('/login')
|
||||
@ -31,11 +31,11 @@ app.route('/login')
|
||||
});
|
||||
```
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project up to this point [here](https://gist.github.com/camperbot/1f7f6f76adb178680246989612bea21e).
|
||||
Invia la tua pagina quando pensi di averlo fatto correttamente. Se dovessi incontrare degli errori, puoi controllare il progetto fino a questo punto [qui](https://gist.github.com/camperbot/1f7f6f76adb178680246989612bea21e).
|
||||
|
||||
# --hints--
|
||||
|
||||
Route /auth/github should be correct.
|
||||
La rotta /auth/github dovrebbe essere corretta.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -53,7 +53,7 @@ Route /auth/github should be correct.
|
||||
);
|
||||
```
|
||||
|
||||
Route /auth/github/callback should be correct.
|
||||
La rotta /auth/github/callback dovrebbe essere corretta.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 58966a17f9fc0f352b528e6d
|
||||
title: Registration of New Users
|
||||
title: Registrazione di nuovi utenti
|
||||
challengeType: 2
|
||||
forumTopicId: 301561
|
||||
dashedName: registration-of-new-users
|
||||
@ -8,11 +8,11 @@ dashedName: registration-of-new-users
|
||||
|
||||
# --description--
|
||||
|
||||
Now we need to allow a new user on our site to register an account. On the `res.render` for the home page add a new variable to the object passed along--`showRegistration: true`. When you refresh your page, you should then see the registration form that was already created in your `index.pug` file! This form is set up to **POST** on `/register`, so this is where we should set up to accept the **POST** and create the user object in the database.
|
||||
Ora dobbiamo permettere ad un nuovo utente di creare un account sul nostro sito. In `res.render` per l'home page aggiungi una nuova variabile all'oggetto passato `showRegistration: true`. Quando aggiorni la pagina, dovresti vedere un modulo di registrazione che era già stato creato nel file `index.pug`! Questo modulo è impostato in modo da mandare una richiesta **POST** su `/register`, quindi è qui che dovremmo accettare le richieste **POST** e creare l'oggetto dell'utente nel database.
|
||||
|
||||
The logic of the registration route should be as follows: Register the new user > Authenticate the new user > Redirect to /profile
|
||||
La logica della rotta di registrazione dovrebbe essere come segue: Registrare il nuovo utente > Autenticare il nuovo utente > Reindirizzamento a /profile
|
||||
|
||||
The logic of step 1, registering the new user, should be as follows: Query database with a findOne command > if user is returned then it exists and redirect back to home *OR* if user is undefined and no error occurs then 'insertOne' into the database with the username and password, and, as long as no errors occur, call *next* to go to step 2, authenticating the new user, which we've already written the logic for in our POST */login* route.
|
||||
La logica dello step 1, registrare un nuovo utente, dovrebbe essere come segue: Fare la richiesta al database con un comando findOne > se l'utente è ritornato allora esiste, e reindirizzare all'home *O* se l'utente non è definito e nessun errore occorre allora inserire l'utente con 'insertOne' nel database con nome utente e password, e finché nessun errore occorre, invocare *next* per andare allo step 2, autenticare il nuovo utente, per cui abbiamo già scritto la logica nella rotta POST */logic*.
|
||||
|
||||
```js
|
||||
app.route('/register')
|
||||
@ -47,13 +47,13 @@ app.route('/register')
|
||||
);
|
||||
```
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/b230a5b3bbc89b1fa0ce32a2aa7b083e).
|
||||
Invia la tua pagina quando pensi di averlo fatto correttamente. Se incontri degli errori, puoi controllare il progetto completato fino a questo punto [qui](https://gist.github.com/camperbot/b230a5b3bbc89b1fa0ce32a2aa7b083e).
|
||||
|
||||
**NOTE:** From this point onwards, issues can arise relating to the use of the *picture-in-picture* browser. If you are using an online IDE which offers a preview of the app within the editor, it is recommended to open this preview in a new tab.
|
||||
**NOTA:** Da questo punto in poi, possono sorgere problemi relativi all'uso del browser *picture-in-picture*. Se stai utilizzando un IDE online che offre una preview dell'app nell'editor, è raccomandato aprire la preview in una nuova scheda.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should register route and display on home.
|
||||
Dovresti registrare il percorso e visualizzare nella home.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -76,7 +76,7 @@ You should register route and display on home.
|
||||
);
|
||||
```
|
||||
|
||||
Registering should work.
|
||||
Deve essere possibile registrarsi.
|
||||
|
||||
```js
|
||||
async (getUserInput) => {
|
||||
@ -104,7 +104,7 @@ async (getUserInput) => {
|
||||
};
|
||||
```
|
||||
|
||||
Login should work.
|
||||
Deve essere possibile autenticarsi.
|
||||
|
||||
```js
|
||||
async (getUserInput) => {
|
||||
@ -153,7 +153,7 @@ async (getUserInput) => {
|
||||
};
|
||||
```
|
||||
|
||||
Logout should work.
|
||||
Deve essere possibile fare logout.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -171,7 +171,7 @@ Logout should work.
|
||||
);
|
||||
```
|
||||
|
||||
Profile should no longer work after logout.
|
||||
Il profilo non deve più essere accessibile dopo aver fatto logout.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589fc832f9fc0f352b528e79
|
||||
title: Send and Display Chat Messages
|
||||
title: Invia e visualizza messaggi di chat
|
||||
challengeType: 2
|
||||
forumTopicId: 301562
|
||||
dashedName: send-and-display-chat-messages
|
||||
@ -8,7 +8,7 @@ dashedName: send-and-display-chat-messages
|
||||
|
||||
# --description--
|
||||
|
||||
It's time you start allowing clients to send a chat message to the server to emit to all the clients! In your `client.js` file, you should see there is already a block of code handling when the message form is submitted.
|
||||
È ora di iniziare a consentire ai client di inviare un messaggio di chat al server da inviare a tutti i client! Nel tuo file `client.js`, dovresti vedere che c'è già un blocco di codice che gestisce quando il modulo invia il messaggio.
|
||||
|
||||
```js
|
||||
$('form').submit(function() {
|
||||
@ -16,23 +16,23 @@ $('form').submit(function() {
|
||||
});
|
||||
```
|
||||
|
||||
Within the form submit code, you should emit an event after you define `messageToSend` but before you clear the text box `#m`. The event should be named `'chat message'` and the data should just be `messageToSend`.
|
||||
All'interno del codice di invio del modulo, dovresti emettere un evento dopo aver definito `messageToSend` ma prima di cancellare la casella di testo `#m`. L'evento dovrebbe essere chiamato `'chat message'` e i dati dovrebbero essere solo `messageToSend`.
|
||||
|
||||
```js
|
||||
socket.emit('chat message', messageToSend);
|
||||
```
|
||||
|
||||
Now, on your server, you should be listening to the socket for the event `'chat message'` with the data being named `message`. Once the event is received, it should emit the event `'chat message'` to all sockets `io.emit` with the data being an object containing `name` and `message`.
|
||||
Ora, sul tuo server, si dovrebbe ascoltare il socket in attesa dell'evento `'chat message'` con i dati chiamati `message`. Una volta ricevuto l'evento, dovrebbe emettere l'evento `'chat message'` a tutti i socket `io.emit` con i dati sotto forma di oggetto contenente `name` e `message`.
|
||||
|
||||
In `client.js`, you should now listen for event `'chat message'` and, when received, append a list item to `#messages` with the name, a colon, and the message!
|
||||
In `client.js`, dovresti ora rimanere in ascolto per l'evento `'chat message'` e, quando ricevuto, aggiungi un elemento di lista a `#messages` con il nome, due punti e il messaggio!
|
||||
|
||||
At this point, the chat should be fully functional and sending messages across all clients!
|
||||
A questo punto, la chat dovrebbe essere completamente funzionante e in grado di inviare messaggi attraverso tutti i client!
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/d7af9864375207e254f73262976d2016).
|
||||
Invia la tua pagina quando pensi di averlo fatto correttamente. Se incontri degli errori, puoi controllare il progetto completato fino a questo punto [qui](https://gist.github.com/camperbot/d7af9864375207e254f73262976d2016).
|
||||
|
||||
# --hints--
|
||||
|
||||
Server should listen for `'chat message'` and then emit it properly.
|
||||
Il server dovrebbe rimanere in ascolto di `'chat message'` ed emetterlo correttamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -50,7 +50,7 @@ Server should listen for `'chat message'` and then emit it properly.
|
||||
);
|
||||
```
|
||||
|
||||
Client should properly handle and display the new data from event `'chat message'`.
|
||||
Il client dovrebbe gestire e visualizzare correttamente i nuovi dati dall'evento `'chat message'`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5895f70bf9fc0f352b528e64
|
||||
title: Use a Template Engine's Powers
|
||||
title: Usare il potere di un Template Engine
|
||||
challengeType: 2
|
||||
forumTopicId: 301567
|
||||
dashedName: use-a-template-engines-powers
|
||||
@ -8,23 +8,23 @@ dashedName: use-a-template-engines-powers
|
||||
|
||||
# --description--
|
||||
|
||||
One of the greatest features of using a template engine is being able to pass variables from the server to the template file before rendering it to HTML.
|
||||
Una delle maggiori caratteristiche dell'utilizzo di un template engine è essere in grado di passare variabili dal server al file modello prima di renderlo in HTML.
|
||||
|
||||
In your Pug file, you're able to use a variable by referencing the variable name as `#{variable_name}` inline with other text on an element or by using an equal sign on the element without a space such as `p=variable_name` which assigns the variable's value to the p element's text.
|
||||
Nel tuo file Pug, sei in grado di usare una variabile facendo riferimento al nome della variabile come `#{variable_name}` inline con un altro testo su un elemento o usando un segno uguale sull'elemento senza uno spazio come `p=variable_name` che assegna il valore della variabile al testo dell'elemento p.
|
||||
|
||||
We strongly recommend looking at the syntax and structure of Pug [here](https://github.com/pugjs/pug) on GitHub's README. Pug is all about using whitespace and tabs to show nested elements and cutting down on the amount of code needed to make a beautiful site.
|
||||
Si consiglia vivamente di guardare la sintassi e la struttura di Pug [qui](https://github.com/pugjs/pug) sul README di GitHub. Pug utilizza spazi bianchi e tab per mostrare elementi annidati e tagliare sulla quantità di codice necessario per fare un bel sito.
|
||||
|
||||
Looking at our pug file 'index.pug' included in your project, we used the variables *title* and *message*.
|
||||
Guardando il nostro file pug 'index.pug' incluso nel tuo progetto, abbiamo usato le variabili *title* e *message*.
|
||||
|
||||
To pass those along from our server, you will need to add an object as a second argument to your *res.render* with the variables and their values. For example, pass this object along setting the variables for your index view: `{title: 'Hello', message: 'Please login'}`
|
||||
Per passare quelle variabili dal nostro server, dovrai aggiungere un oggetto come secondo argomento ai tuoi *res.render* con le variabili e i loro valori. Per esempio, passa questo oggetto impostando le variabili per la tua vista indice: `{title: 'Hello', message: 'Please login'}`
|
||||
|
||||
It should look like: `res.render(process.cwd() + '/views/pug/index', {title: 'Hello', message: 'Please login'});` Now refresh your page and you should see those values rendered in your view in the correct spot as laid out in your index.pug file!
|
||||
Dovrebbe assomigliare a: `res.render(process.cwd() + '/views/pug/index', {title: 'Hello', message: 'Please login'});` Ora aggiorna la tua pagina e dovresti vedere quei valori renderizzati nella tua vista nel punto corretto come impostato nel tuo file index.pug!
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/4af125119ed36e6e6a8bb920db0c0871).
|
||||
Invia la tua pagina quando pensi di averlo fatto correttamente. Se incontri degli errori, puoi controllare il progetto completato fino a questo punto [qui](https://gist.github.com/camperbot/4af125119ed36e6e6a8bb920db0c0871).
|
||||
|
||||
# --hints--
|
||||
|
||||
Pug should correctly render variables.
|
||||
Il Pug dovrebbe visualizzare correttamente le variabili.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -101,19 +101,11 @@ Enviar o formulário deve executar `handleSubmit` o qual deve definir a propried
|
||||
`handleSubmit` deve chamar `event.preventDefault`
|
||||
|
||||
```js
|
||||
const handleSubmit = MyForm.prototype.handleSubmit.toString();
|
||||
const allMatches = handleSubmit.match(/\bevent\.preventDefault\(\s*?\)/g) ?? [];
|
||||
const blockCommented = handleSubmit.match(
|
||||
/\/\*.*?\bevent\.preventDefault\(\s*?\).*?\*\//gs
|
||||
);
|
||||
const lineCommented = handleSubmit.match(
|
||||
/\/\/.*?\bevent\.preventDefault\(\s*?\)/g
|
||||
);
|
||||
const commentedMatches = [...(blockCommented ?? []), ...(lineCommented ?? [])];
|
||||
|
||||
assert(
|
||||
// At least one event.preventDefault() call exists and is not commented out
|
||||
allMatches.length > commentedMatches.length
|
||||
__helpers.isCalledWithNoArgs(
|
||||
'event.preventDefault',
|
||||
MyForm.prototype.handleSubmit.toString()
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036181
|
||||
title: Introducing Inline Styles
|
||||
title: Introduzindo Estilos Em linha
|
||||
challengeType: 6
|
||||
forumTopicId: 301395
|
||||
dashedName: introducing-inline-styles
|
||||
@ -8,33 +8,33 @@ dashedName: introducing-inline-styles
|
||||
|
||||
# --description--
|
||||
|
||||
There are other complex concepts that add powerful capabilities to your React code. But you may be wondering about the more simple problem of how to style those JSX elements you create in React. You likely know that it won't be exactly the same as working with HTML because of [the way you apply classes to JSX elements](/learn/front-end-libraries/react/define-an-html-class-in-jsx).
|
||||
Existem outros conceitos complexos que adicionam recursos poderosos ao seu código React. Mas você pode estar se perguntando sobre o problema mais simples de como estilizar esses elementos JSX que você cria em React. Você provavelmente sabe que não será exatamente o mesmo que trabalhar com HTML por causa [da forma como aplica classes aos elementos JSX](/learn/front-end-libraries/react/define-an-html-class-in-jsx).
|
||||
|
||||
If you import styles from a stylesheet, it isn't much different at all. You apply a class to your JSX element using the `className` attribute, and apply styles to the class in your stylesheet. Another option is to apply inline styles, which are very common in ReactJS development.
|
||||
Se você importar estilos de uma folha de estilos, não é muito diferente de jeito nenhum. Você aplica uma classe ao seu elemento JSX usando o atributo `className` e aplica estilos à classe em sua folha de estilos. Outra opção é aplicar estilos em linha, que são muito comuns no desenvolvimento de ReactJS.
|
||||
|
||||
You apply inline styles to JSX elements similar to how you do it in HTML, but with a few JSX differences. Here's an example of an inline style in HTML:
|
||||
Você aplica estilos em linha em elementos JSX similares a como você faz isso em HTML, mas com algumas diferenças em JSX. Aqui está um exemplo de estilo embutido em HTML:
|
||||
|
||||
```jsx
|
||||
<div style="color: yellow; font-size: 16px">Mellow Yellow</div>
|
||||
```
|
||||
|
||||
JSX elements use the `style` attribute, but because of the way JSX is transpiled, you can't set the value to a `string`. Instead, you set it equal to a JavaScript `object`. Here's an example:
|
||||
Elementos JSX usam o atributo </code>style`, mas por causa da forma como o JSX é transpilado, você não pode definir o valor para uma <code>string`. Em vez disso, você o definiu para ser igual a um `objeto` JavaScript. Exemplo:
|
||||
|
||||
```jsx
|
||||
<div style={{color: "yellow", fontSize: 16}}>Mellow Yellow</div>
|
||||
```
|
||||
|
||||
Notice how we camelCase the `fontSize` property? This is because React will not accept kebab-case keys in the style object. React will apply the correct property name for us in the HTML.
|
||||
Percebeu como colocamos em camelCase a propriedade `fontSize`? Isso é porque o React não aceitará chaves de caso kebab, no objeto de estilo. React aplicará o nome de propriedade correto para nós no HTML.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add a `style` attribute to the `div` in the code editor to give the text a color of red and font size of `72px`.
|
||||
Adicione um atributo `style` para o `div` no editor de código para dar ao texto a cor vermelha e tamanho da fonte de `72px`.
|
||||
|
||||
Note that you can optionally set the font size to be a number, omitting the units `px`, or write it as `72px`.
|
||||
Note que você pode opcionalmente definir o tamanho da fonte como um número. omitindo as unidades `px`, ou escreva-o como `72px`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The component should render a `div` element.
|
||||
O componente deve renderizar um elemento `div`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -45,7 +45,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `div` element should have a color of `red`.
|
||||
O elemento `div` deve ter a cor `vermelha`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -56,7 +56,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `div` element should have a font size of `72px`.
|
||||
O elemento `div` deve ter um tamanho de fonte de `72px`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403617b
|
||||
title: Pass a Callback as Props
|
||||
title: Passe um Callback como Props
|
||||
challengeType: 6
|
||||
forumTopicId: 301400
|
||||
dashedName: pass-a-callback-as-props
|
||||
@ -8,17 +8,17 @@ dashedName: pass-a-callback-as-props
|
||||
|
||||
# --description--
|
||||
|
||||
You can pass `state` as props to child components, but you're not limited to passing data. You can also pass handler functions or any method that's defined on a React component to a child component. This is how you allow child components to interact with their parent components. You pass methods to a child just like a regular prop. It's assigned a name and you have access to that method name under `this.props` in the child component.
|
||||
Você pode passar `state` como "props" para componentes filho, mas você não se limita a passar os dados. Você também pode passar funções manipuladoras ou qualquer método definido em um componente React para um componente filho. É assim que você permite que componentes filhos interajam com seus componentes pai. Você passa métodos para uma criança como uma propriedade regular. Tem um nome atribuído e você tem acesso a esse nome de método sob `this.props` no componente filho.
|
||||
|
||||
# --instructions--
|
||||
|
||||
There are three components outlined in the code editor. The `MyApp` component is the parent that will render the `GetInput` and `RenderInput` child components. Add the `GetInput` component to the render method in `MyApp`, then pass it a prop called `input` assigned to `inputValue` from `MyApp`'s `state`. Also create a prop called `handleChange` and pass the input handler `handleChange` to it.
|
||||
Existem três componentes delineados no editor de código. O componente `MyApp` é o pai que irá renderizar os componentes filhos `GetInput` e `RenderInput`. Adicione o componente `GetInput` ao método de renderização no `MyApp`, então passe uma propriedade chamada `input` atribuída a `inputValue` do `state` do `MyApp`. Também crie uma propriedade chamada `handleChange` e passe o manipulador de evento `handleChange` para ele.
|
||||
|
||||
Next, add `RenderInput` to the render method in `MyApp`, then create a prop called `input` and pass the `inputValue` from `state` to it. Once you are finished you will be able to type in the `input` field in the `GetInput` component, which then calls the handler method in its parent via props. This updates the input in the `state` of the parent, which is passed as props to both children. Observe how the data flows between the components and how the single source of truth remains the `state` of the parent component. Admittedly, this example is a bit contrived, but should serve to illustrate how data and callbacks can be passed between React components.
|
||||
Em seguida, adicione `RenderInput` para o método render em `MyApp`, em seguida crie uma propriedade chamada `input` e passe o `inputValue` de `state` para ela. Depois de terminar, você será capaz de digitar no campo `input` no componente `GetInput`, que então chama o método manipulador em seu pai via props. Isso atualiza a entrada no `state` do pai, que é passado como "props" para ambos os filhos. Observe como os dados fluem entre os componentes e como a única fonte da verdade permanece o `state` do componente pai. Reconheço que esse exemplo é um pouco inventado, mas deve servir para ilustrar como dados e callbacks podem ser passados entre componentes React.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `MyApp` component should render.
|
||||
O componente `MyApp` deve ser renderizado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -29,7 +29,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `GetInput` component should render.
|
||||
O componente `GetInput` deve renderizar.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -40,7 +40,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `RenderInput` component should render.
|
||||
O componente `RenderInput` deve renderizar.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -51,7 +51,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `GetInput` component should receive the `MyApp` state property `inputValue` as props and contain an `input` element which modifies `MyApp` state.
|
||||
O componente `GetInput` deve receber a propriedade state `inputValue` de `MyApp` como props e conter um elemento `input` que modifique o state de `MyApp`.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
@ -74,7 +74,7 @@ async () => {
|
||||
};
|
||||
```
|
||||
|
||||
The `RenderInput` component should receive the `MyApp` state property `inputValue` as props.
|
||||
O componente `RenderInput` deve receber a propriedade state `inputValue` de `MyApp` como props.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403616a
|
||||
title: Pass an Array as Props
|
||||
title: Passe um Array como Props
|
||||
challengeType: 6
|
||||
forumTopicId: 301401
|
||||
dashedName: pass-an-array-as-props
|
||||
@ -8,7 +8,7 @@ dashedName: pass-an-array-as-props
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge demonstrated how to pass information from a parent component to a child component as `props` or properties. This challenge looks at how arrays can be passed as `props`. To pass an array to a JSX element, it must be treated as JavaScript and wrapped in curly braces.
|
||||
O último desafio demonstrou como passar informações de um componente pai para um componente filho como propriedades `props`. Este desafio analisa como matrizes podem ser passadas como `props`. Para passar um array para um elemento JSX, ele deve ser tratado como JavaScript e encapsulado em chaves.
|
||||
|
||||
```jsx
|
||||
<ParentComponent>
|
||||
@ -16,15 +16,15 @@ The last challenge demonstrated how to pass information from a parent component
|
||||
</ParentComponent>
|
||||
```
|
||||
|
||||
The child component then has access to the array property `colors`. Array methods such as `join()` can be used when accessing the property. `const ChildComponent = (props) => <p>{props.colors.join(', ')}</p>` This will join all `colors` array items into a comma separated string and produce: `<p>green, blue, red</p>` Later, we will learn about other common methods to render arrays of data in React.
|
||||
O componente filho então tem acesso às propriedades `colors` do array. Métodos de array como `join()` podem ser usados ao acessar a propriedade. `const ChildComponent = (props) => <p>{props.colors. oin(', ')}</p>` Isto irá juntar todas os itens do array `colors` em uma string separada por vírgulas e produzir: `<p>green, blue, red</p>` Mais tarde, aprenderemos sobre outros métodos comuns para renderizar arrays de dados em React.
|
||||
|
||||
# --instructions--
|
||||
|
||||
There are `List` and `ToDo` components in the code editor. When rendering each `List` from the `ToDo` component, pass in a `tasks` property assigned to an array of to-do tasks, for example `["walk dog", "workout"]`. Then access this `tasks` array in the `List` component, showing its value within the `p` element. Use `join(", ")` to display the `props.tasks`array in the `p` element as a comma separated list. Today's list should have at least 2 tasks and tomorrow's should have at least 3 tasks.
|
||||
Existem os componentes `List` e `ToDo` no editor de código. Ao renderizar cada `List` do componente `ToDo`, passe em uma propriedade `tasks` atribuída a um array de tarefas a fazer, por exemplo `["walk dog", "workout"]`. Em seguida, acesse o array `tasks` no componente `List`, mostrando seu valor dentro do elemento `p`. Use `join(", ")` para exibir o array `props.tasks` no elemento `p` como uma lista separada por vírgulas. A lista de hoje deveria ter pelo menos 2 tarefas e a de amanhã deveria ter pelo menos 3 tarefas.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `ToDo` component should return a single outer `div`.
|
||||
O componente `ToDo` deve retornar um único `div` externo.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -35,7 +35,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The third child of the `ToDo` component should be an instance of the `List` component.
|
||||
O terceiro filho do componente `ToDo` deve ser uma instância do componente `List`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -46,7 +46,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The fifth child of the `ToDo` component should be an instance of the `List` component.
|
||||
O quinto filho do componente `ToDo` deve ser uma instância do componente `List`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -57,7 +57,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Both instances of the `List` component should have a property called `tasks` and `tasks` should be of type array.
|
||||
Ambas as instâncias do componente `List` devem ter uma propriedade chamada `tasks` e `tasks` devem ser do tipo array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -71,7 +71,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The first `List` component representing the tasks for today should have 2 or more items.
|
||||
O primeiro componente `List` que representa as tarefas para hoje deve ter 2 ou mais itens.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -82,7 +82,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The second `List` component representing the tasks for tomorrow should have 3 or more items.
|
||||
O segundo componente `List` que representa as tarefas para amanhã deve ter 3 ou mais itens.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -93,7 +93,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `List` component should render the value from the `tasks` prop in the `p` tag.
|
||||
O componente `List` deve renderizar o valor da propriedade `tasks` na tag `p`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036169
|
||||
title: Pass Props to a Stateless Functional Component
|
||||
title: Passar Props para um Componente Funcional Sem Estado
|
||||
challengeType: 6
|
||||
forumTopicId: 301402
|
||||
dashedName: pass-props-to-a-stateless-functional-component
|
||||
@ -8,7 +8,7 @@ dashedName: pass-props-to-a-stateless-functional-component
|
||||
|
||||
# --description--
|
||||
|
||||
The previous challenges covered a lot about creating and composing JSX elements, functional components, and ES6 style class components in React. With this foundation, it's time to look at another feature very common in React: **props**. In React, you can pass props, or properties, to child components. Say you have an `App` component which renders a child component called `Welcome` which is a stateless functional component. You can pass `Welcome` a `user` property by writing:
|
||||
Os desafios anteriores cobriram muito sobre a criação e composição de elementos JSX, componentes funcionais e componentes de classe de estilo ES6 no React. Com esta fundação, é hora de olhar outro recurso muito comum em React: **props**. No React, você pode passar props, ou propriedades, para componentes filhos. Digamos que você tem um componente `App` que renderiza um componente filho chamado `Welcome` que é um componente funcional sem estado. Você pode passar a `Welcome` uma propriedade `user` escrevendo:
|
||||
|
||||
```jsx
|
||||
<App>
|
||||
@ -16,21 +16,21 @@ The previous challenges covered a lot about creating and composing JSX elements,
|
||||
</App>
|
||||
```
|
||||
|
||||
You use **custom HTML attributes** created by you and supported by React to be passed to the component. In this case, the created property `user` is passed to the component `Welcome`. Since `Welcome` is a stateless functional component, it has access to this value like so:
|
||||
Você usa **atributos HTML personalizados** criados por você e suportados por React para serem passados ao componente. Neste caso, a propriedade criada `user` é passada para o componente `Welcome`. Uma vez que `Welcome` é um componente funcional sem estado, ele tem acesso a esse valor assim:
|
||||
|
||||
```jsx
|
||||
const Welcome = (props) => <h1>Hello, {props.user}!</h1>
|
||||
```
|
||||
|
||||
It is standard to call this value `props` and when dealing with stateless functional components, you basically consider it as an argument to a function which returns JSX. You can access the value of the argument in the function body. With class components, you will see this is a little different.
|
||||
É padrão chamar esse valor `"props"` e, quando lidar com componentes funcionais sem estado, você basicamente considera isso como um argumento para uma função que retorna JSX. Você pode acessar o valor do argumento no corpo da função. Com componentes de classe, você verá que isto é um pouco diferente.
|
||||
|
||||
# --instructions--
|
||||
|
||||
There are `Calendar` and `CurrentDate` components in the code editor. When rendering `CurrentDate` from the `Calendar` component, pass in a property of `date` assigned to the current date from JavaScript's `Date` object. Then access this `prop` in the `CurrentDate` component, showing its value within the `p` tags. Note that for `prop` values to be evaluated as JavaScript, they must be enclosed in curly brackets, for instance `date={Date()}`.
|
||||
Existe no editor de código os componentes `Calendar` e `CurrentDate`. Ao renderizar `CurrentDate` do componente `Calendar`, passe em uma propriedade `date` atribuída à data atual a partir do objeto `Date` do JavaScript. Em seguida, acesse essa `prop` no componente `CurrentDate`, mostrando seu valor dentro das tags `p`. Note que para que os valores de `prop` sejam avaliados como JavaScript, eles devem ser colocados entre chaves, por exemplo, `date={Date()}`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `Calendar` component should return a single `div` element.
|
||||
O componente `Calendar` deve retornar um único elemento `div`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -41,7 +41,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The second child of the `Calendar` component should be the `CurrentDate` component.
|
||||
O segundo filho do componente `Calendar` deve ser o componente `CurrentDate`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -52,7 +52,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `CurrentDate` component should have a prop called `date`.
|
||||
O componente `CurrentDate` deve ter uma prop chamada `date`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -63,7 +63,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `date` prop of the `CurrentDate` should contain a string of text.
|
||||
A propriedade `date` de `CurrentDate` deve conter uma string de texto.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -75,13 +75,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `date` prop should be generated by calling `Date()`
|
||||
A propriedade `date` deve ser gerada chamando `Date()`
|
||||
|
||||
```js
|
||||
assert(/<CurrentDatedate={Date\(\)}\/>/.test(__helpers.removeWhiteSpace(code)));
|
||||
```
|
||||
|
||||
The `CurrentDate` component should render the value from the `date` prop in the `p` tag.
|
||||
O componente `CurrentDate` deve renderizar o valor da prop `date` na tag `p`.
|
||||
|
||||
```js
|
||||
let date = 'dummy date';
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403617a
|
||||
title: Pass State as Props to Child Components
|
||||
title: Passar State como Props para Componentes Filhos
|
||||
challengeType: 6
|
||||
forumTopicId: 301403
|
||||
dashedName: pass-state-as-props-to-child-components
|
||||
@ -8,19 +8,19 @@ dashedName: pass-state-as-props-to-child-components
|
||||
|
||||
# --description--
|
||||
|
||||
You saw a lot of examples that passed props to child JSX elements and child React components in previous challenges. You may be wondering where those props come from. A common pattern is to have a stateful component containing the `state` important to your app, that then renders child components. You want these components to have access to some pieces of that `state`, which are passed in as props.
|
||||
Você viu muitos exemplos que passaram "props" para elementos JSX filhos e componentes filho React em desafios anteriores. Você pode estar se perguntando de onde vêm essas props. Um padrão comum é ter um componente com estado contendo o `state` importante para o seu aplicativo, que depois renderiza componentes filhos. Você quer que esses componentes tenham acesso a alguns pedaços desse `state`, que são passados como "props".
|
||||
|
||||
For example, maybe you have an `App` component that renders a `Navbar`, among other components. In your `App`, you have `state` that contains a lot of user information, but the `Navbar` only needs access to the user's username so it can display it. You pass that piece of `state` to the `Navbar` component as a prop.
|
||||
Por exemplo, talvez você tenha um componente `App` que renderiza uma `Navbar`, entre outros componentes. No seu `App`, você tem `state` que contém muitas informações de usuário, mas a barra de `Navbar` só precisa acessar o nome de usuário para que possa exibi-lo. Você passa esse pedaço de `state` para o componente `Navbar` como uma prop.
|
||||
|
||||
This pattern illustrates some important paradigms in React. The first is *unidirectional data flow*. State flows in one direction down the tree of your application's components, from the stateful parent component to child components. The child components only receive the state data they need. The second is that complex stateful apps can be broken down into just a few, or maybe a single, stateful component. The rest of your components simply receive state from the parent as props, and render a UI from that state. It begins to create a separation where state management is handled in one part of code and UI rendering in another. This principle of separating state logic from UI logic is one of React's key principles. When it's used correctly, it makes the design of complex, stateful applications much easier to manage.
|
||||
Este padrão ilustra alguns paradigmas importantes em React. O primeiro é um *fluxo de dados unidirecional*. Estado flui em uma direção para baixo na árvore dos componentes da sua aplicação, do componente pai stateful para componentes filho. Os componentes filhos só recebem os dados do estado de que precisam. O segundo é que aplicativos de estado complexos podem ser divididos em apenas alguns, ou talvez um único componente com estado. O resto dos seus componentes simplesmente recebem o state do pai como "props" e renderizam uma interface desse estado. Ele começa a criar uma separação onde o gerenciamento de estado é tratado em uma parte do código e renderização de interface em outra. Este princípio da separação da lógica do estado da lógica da interface do usuário é um dos princípios fundamentais do React. Quando usado corretamente, torna o design de aplicações complexas e com estado muito mais fácil de gerenciar.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The `MyApp` component is stateful and renders a `Navbar` component as a child. Pass the `name` property in its `state` down to the child component, then show the `name` in the `h1` tag that's part of the `Navbar` render method. `name` should appear after the text `Hello, my name is:`.
|
||||
O componente `MyApp` é stateful e renderiza um componente `Navbar` como filho. Passe a propriedade `name` em seu `state` até o componente filho, em seguida, mostre o `name` na tag `h1` que faz parte da renderização do `Navbar`. `name` deve aparecer após o texto `Hello, my name is:`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `MyApp` component should render with a `Navbar` component inside.
|
||||
O componente `MyApp` deve renderizar com um componente `Navbar` dentro dele.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -34,7 +34,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Navbar` component should receive the `MyApp` state property `name` as props.
|
||||
O componente `Navbar` deve receber a propriedade `MyApp` state `name` como props.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
@ -50,7 +50,7 @@ async () => {
|
||||
};
|
||||
```
|
||||
|
||||
The `h1` element in `Navbar` should render the `name` prop.
|
||||
O elemento `h1` na `Navbar` deve renderizar a prop `name`.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036167
|
||||
title: Render a Class Component to the DOM
|
||||
title: Renderizar um Componente de Classe para o DOM
|
||||
challengeType: 6
|
||||
forumTopicId: 301404
|
||||
dashedName: render-a-class-component-to-the-dom
|
||||
@ -8,19 +8,19 @@ dashedName: render-a-class-component-to-the-dom
|
||||
|
||||
# --description--
|
||||
|
||||
You may remember using the ReactDOM API in an earlier challenge to render JSX elements to the DOM. The process for rendering React components will look very similar. The past few challenges focused on components and composition, so the rendering was done for you behind the scenes. However, none of the React code you write will render to the DOM without making a call to the ReactDOM API.
|
||||
Você talvez se lembre de usar a API do ReactDOM em um desafio anterior para renderizar elementos JSX para o DOM. O processo para renderizar componentes React ficará muito parecido. Os últimos desafios focaram em componentes e composição, então a renderização foi feita pra você nos bastidores. No entanto, nenhum código React que você escreva irá renderizar no DOM sem fazer uma chamada para a API do ReactDOM.
|
||||
|
||||
Here's a refresher on the syntax: `ReactDOM.render(componentToRender, targetNode)`. The first argument is the React component that you want to render. The second argument is the DOM node that you want to render that component within.
|
||||
Aqui está uma atualização na sintaxe: `ReactDOM.render(componentToRender, targetNode)`. O primeiro argumento é o componente React que você deseja renderizar. O segundo argumento é o nó DOM onde você quer renderizar esse componente dentro.
|
||||
|
||||
React components are passed into `ReactDOM.render()` a little differently than JSX elements. For JSX elements, you pass in the name of the element that you want to render. However, for React components, you need to use the same syntax as if you were rendering a nested component, for example `ReactDOM.render(<ComponentToRender />, targetNode)`. You use this syntax for both ES6 class components and functional components.
|
||||
Componentes React são passados a `ReactDOM.render()` um pouco diferente dos elementos JSX. Para elementos JSX, você passa o nome do elemento que deseja renderizar. No entanto, para componentes React, você precisa usar a mesma sintaxe como se estivesse renderizando um componente aninhado, por exemplo `ReactDOM. ender(<ComponentToRender />, targetNode)`. Você usa esta sintaxe para componentes de classe ES6 e componentes funcionais.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Both the `Fruits` and `Vegetables` components are defined for you behind the scenes. Render both components as children of the `TypesOfFood` component, then render `TypesOfFood` to the DOM. There is a `div` with `id='challenge-node'` available for you to use.
|
||||
Tanto os componentes `Fruits` e `Vegetables` são definidos para você nos bastidores. Renderize ambos os componentes como filhos do componente `TypesOfFood` e, em seguida, renderizar `TypesOfFood` para o DOM. Há um `div` com `id='challenge-node'` disponível para você usar.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `TypesOfFood` component should return a single `div` element.
|
||||
O componente `TypesOfFood` deve retornar um único elemento `div`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -31,7 +31,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `TypesOfFood` component should render the `Fruits` component after the `h1` element.
|
||||
O componente `TypesOfFood` deve renderizar o componente `Fruits` após o elemento `h1`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `TypesOfFood` component should render the `Vegetables` component after `Fruits`.
|
||||
O componente `TypesOfFood` deve renderizar o componente `Vegetables` depois de `Fruits`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -53,7 +53,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `TypesOfFood` component should render to the DOM within the `div` with the id `challenge-node`.
|
||||
O componente `TypesOfFood` deve ser renderizado no DOM dentro do `div` com o id `challenge-node`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036188
|
||||
title: Render Conditionally from Props
|
||||
title: Renderizar Condicionalmente das Props
|
||||
challengeType: 6
|
||||
forumTopicId: 301405
|
||||
dashedName: render-conditionally-from-props
|
||||
@ -8,21 +8,21 @@ dashedName: render-conditionally-from-props
|
||||
|
||||
# --description--
|
||||
|
||||
So far, you've seen how to use `if/else`, `&&`, and the ternary operator (`condition ? expressionIfTrue : expressionIfFalse`) to make conditional decisions about what to render and when. However, there's one important topic left to discuss that lets you combine any or all of these concepts with another powerful React feature: props. Using props to conditionally render code is very common with React developers — that is, they use the value of a given prop to automatically make decisions about what to render.
|
||||
Até agora, você viu como usar o `if/else`, `&&`, e o operador ternário (`condição ? expressãoSeVerdadeiro: expressãoSeFalso`) para tomar decisões condicionais sobre o que renderizar e quando. No entanto, resta um tópico importante para discutir que permite que você combine todos esses conceitos com outro poderoso recurso React: props. Usar props para renderizar condicionalmente código é muito comum entre desenvolvedores React — isto é, eles usam o valor de uma determinada propriedade para tomar decisões automaticamente sobre o que renderizar.
|
||||
|
||||
In this challenge, you'll set up a child component to make rendering decisions based on props. You'll also use the ternary operator, but you can see how several of the other concepts that were covered in the last few challenges might be just as useful in this context.
|
||||
Neste desafio, você vai configurar um componente filho para tomar decisões de renderização com base em props. Você também usará o operador ternário, mas você pode ver como vários dos outros conceitos que foram abordados nos últimos desafios poderão ser igualmente úteis neste contexto.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor has two components that are partially defined for you: a parent called `GameOfChance`, and a child called `Results`. They are used to create a simple game where the user presses a button to see if they win or lose.
|
||||
O editor de código tem dois componentes que estão parcialmente definidos para você: um pai chamado `GameOfChance`, e uma filho chamado `Results`. Eles são usados para criar um jogo simples onde o usuário pressiona um botão para ver se ele vence ou perde.
|
||||
|
||||
First, you'll need a simple expression that randomly returns a different value every time it is run. You can use `Math.random()`. This method returns a value between `0` (inclusive) and `1` (exclusive) each time it is called. So for 50/50 odds, use `Math.random() >= .5` in your expression. Statistically speaking, this expression will return `true` 50% of the time, and `false` the other 50%. In the render method, replace `null` with the above expression to complete the variable declaration.
|
||||
Primeiro, você precisará de uma expressão simples que retorna aleatoriamente um valor diferente toda vez que for executado. Você pode usar `Math.random()`. Esse método retorna um valor entre `0` (inclusivo) e `1` (exclusivo) a cada vez que é chamado. Portanto, para probabilidades 50/50, use `Math.random() >= .5` na sua expressão. Estatísticas falando, essa expressão retornará `verdadeiro` 50% das vezes, e `falso` os outros 50%. No método de renderização, substitua `null` pela expressão acima para completar a declaração de variável.
|
||||
|
||||
Now you have an expression that you can use to make a randomized decision in the code. Next you need to implement this. Render the `Results` component as a child of `GameOfChance`, and pass in `expression` as a prop called `fiftyFifty`. In the `Results` component, write a ternary expression to render the `h1` element with the text `You Win!` or `You Lose!` based on the `fiftyFifty` prop that's being passed in from `GameOfChance`. Finally, make sure the `handleClick()` method is correctly counting each turn so the user knows how many times they've played. This also serves to let the user know the component has actually updated in case they win or lose twice in a row.
|
||||
Agora você tem uma expressão que pode usar para tomar uma decisão aleatória no código. Em seguida, você precisa implementar isso. Renderize o componente `Results` como filho de `GameOfChance`, e passe `expression` como uma prop chamada `fiftyFifty`. No componente `Results`, escreva uma expressão ternária para renderizar o elemento `h1` com o texto `You Win!` ou `You Lose!` baseado na prop `fiftyFifty` que está sendo passada de `GameOfChance`. Finalmente, certifique-se de que o método `handleClick()` está contando corretamente cada turno para que o usuário saiba quantas vezes jogou. Isso também serve para que o usuário saiba que o componente realmente atualizou caso vença ou perca duas vezes consecutivas.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `GameOfChance` component should exist and render to the page.
|
||||
O componente `GameOfChance` deve existir e renderizar à página.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -31,7 +31,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`GameOfChance` should return a single `button` element.
|
||||
`GameOfChance` deve retornar um único elemento `button`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -40,7 +40,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`GameOfChance` should return a single instance of the `Results` component, which has a prop called `fiftyFifty`.
|
||||
`GameOfChance` deve retornar uma única instância do componente `Results`, que tem uma prop chamada `fiftyFifty`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -53,7 +53,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`GameOfChance` state should be initialized with a property of `counter` set to a value of `1`.
|
||||
O state de `GameOfChance` deve ser inicializado com a propriedade `counter` definida com o valor `1`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -62,7 +62,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
When the `GameOfChance` component is first rendered to the DOM, a `p` element should be returned with the inner text of `Turn: 1`.
|
||||
Quando o componente `GameOfChance` é renderizado pela primeira vez para o DOM, um elemento `p` deve ser retornado com o texto interno de `Turn: 1`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -71,7 +71,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
Each time the button is clicked, the counter state should be incremented by a value of 1, and a single `p` element should be rendered to the DOM that contains the text `Turn: N`, where `N` is the value of the counter state.
|
||||
Cada vez que o botão é clicado, o estado do contador deve ser incrementado por um valor de 1, e um único elemento `p` deve ser renderizado para o DOM que contém o texto `Turn: N`, onde `N` é o valor do estado contador.
|
||||
|
||||
```js
|
||||
(() => {
|
||||
@ -123,7 +123,7 @@ Each time the button is clicked, the counter state should be incremented by a va
|
||||
})();
|
||||
```
|
||||
|
||||
When the `GameOfChance` component is first mounted to the DOM and each time the button is clicked thereafter, a single `h1` element should be returned that randomly renders either `You Win!` or `You Lose!`.
|
||||
Quando o componente `GameOfChance` é montado pela primeira vez no DOM e toda vez que o botão é clicado depois, um único elemento `h1` deve ser retornado que renderiza aleatoriamente qualquer um dos textos `You Win!` ou `You Lose!`.
|
||||
|
||||
```js
|
||||
(() => {
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24bbe0dba28a8d3cbd4c5f
|
||||
title: Render HTML Elements to the DOM
|
||||
title: Renderizar elementos HTML para o DOM
|
||||
challengeType: 6
|
||||
forumTopicId: 301406
|
||||
dashedName: render-html-elements-to-the-dom
|
||||
@ -8,37 +8,37 @@ dashedName: render-html-elements-to-the-dom
|
||||
|
||||
# --description--
|
||||
|
||||
So far, you've learned that JSX is a convenient tool to write readable HTML within JavaScript. With React, we can render this JSX directly to the HTML DOM using React's rendering API known as ReactDOM.
|
||||
Até agora, você aprendeu que JSX é uma ferramenta conveniente para escrever HTML legível dentro de JavaScript. Com React, podemos renderizar esse JSX diretamente para o DOM HTML usando a API de renderização do React conhecida como ReactDOM.
|
||||
|
||||
ReactDOM offers a simple method to render React elements to the DOM which looks like this: `ReactDOM.render(componentToRender, targetNode)`, where the first argument is the React element or component that you want to render, and the second argument is the DOM node that you want to render the component to.
|
||||
ReactDOM oferece um método simples para renderizar elementos React para o DOM que se parece com isso: `ReactDOM.render(componentToRender, targetNode)`, onde o primeiro argumento é o elemento ou componente que você deseja renderizar, e o segundo argumento é o nó do DOM onde você deseja renderizar o componente.
|
||||
|
||||
As you would expect, `ReactDOM.render()` must be called after the JSX element declarations, just like how you must declare variables before using them.
|
||||
Como você esperaria, `ReactDOM.render()` deve ser chamado após as declarações dos elementos JSX, assim como você deve declarar variáveis antes de usá-las.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor has a simple JSX component. Use the `ReactDOM.render()` method to render this component to the page. You can pass defined JSX elements directly in as the first argument and use `document.getElementById()` to select the DOM node to render them to. There is a `div` with `id='challenge-node'` available for you to use. Make sure you don't change the `JSX` constant.
|
||||
O editor de código tem um componente JSX simples. Use o método `ReactDOM.render()` para renderizar este componente na página. Você pode passar elementos JSX definidos diretamente como o primeiro argumento e usar `document.getElementById()` para selecionar o nó do DOM onde renderizá-los. Há um `div` com `id='challenge-node'` disponível para você usar. Certifique-se de não alterar a constante `JSX`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The constant `JSX` should return a `div` element.
|
||||
A constante `JSX` deve retornar um elemento `div`.
|
||||
|
||||
```js
|
||||
assert(JSX.type === 'div');
|
||||
```
|
||||
|
||||
The `div` should contain an `h1` tag as the first element.
|
||||
O `div` deve conter uma tag `h1` como o primeiro elemento.
|
||||
|
||||
```js
|
||||
assert(JSX.props.children[0].type === 'h1');
|
||||
```
|
||||
|
||||
The `div` should contain a `p` tag as the second element.
|
||||
O `div` deve conter uma tag `p` como segundo elemento.
|
||||
|
||||
```js
|
||||
assert(JSX.props.children[1].type === 'p');
|
||||
```
|
||||
|
||||
The provided JSX element should render to the DOM node with id `challenge-node`.
|
||||
O elemento JSX fornecido deve renderizar ao nó do DOM com id `challenge-node`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403618d
|
||||
title: Render React on the Server with renderToString
|
||||
title: Renderizar React no Servidor com renderToString
|
||||
challengeType: 6
|
||||
forumTopicId: 301407
|
||||
dashedName: render-react-on-the-server-with-rendertostring
|
||||
@ -8,17 +8,17 @@ dashedName: render-react-on-the-server-with-rendertostring
|
||||
|
||||
# --description--
|
||||
|
||||
So far, you have been rendering React components on the client. Normally, this is what you will always do. However, there are some use cases where it makes sense to render a React component on the server. Since React is a JavaScript view library and you can run JavaScript on the server with Node, this is possible. In fact, React provides a `renderToString()` method you can use for this purpose.
|
||||
Até agora, você tem renderizado componentes React no cliente. Normalmente, é isso o que você sempre fará. No entanto, há alguns casos de uso em que faz sentido renderizar um componente React no servidor. Uma vez que React é uma biblioteca de visualização do JavaScript e você pode executar JavaScript no servidor com Node, isso é possível. De fato, React fornece um método `renderToString()` que você pode usar para este propósito.
|
||||
|
||||
There are two key reasons why rendering on the server may be used in a real world app. First, without doing this, your React apps would consist of a relatively empty HTML file and a large bundle of JavaScript when it's initially loaded to the browser. This may not be ideal for search engines that are trying to index the content of your pages so people can find you. If you render the initial HTML markup on the server and send this to the client, the initial page load contains all of the page's markup which can be crawled by search engines. Second, this creates a faster initial page load experience because the rendered HTML is smaller than the JavaScript code of the entire app. React will still be able to recognize your app and manage it after the initial load.
|
||||
Existem duas principais razões pelas quais a renderização no servidor pode ser usada em um aplicativo do mundo real. Primeiro, sem fazer isso, seus aplicativos React consistiriam de um arquivo HTML relativamente vazio e um grande pacote de JavaScript quando inicialmente é carregado ao navegador. Isso pode não ser ideal para motores de busca que estão tentando indexar o conteúdo das suas páginas para que as pessoas possam te encontrar. Se você renderizar a marcação HTML inicial no servidor e enviar para o cliente, a carga inicial da página contém todas as marcações da página que podem ser rastreadas por motores de busca. Em segundo lugar, isso cria uma experiência de carregamento de página inicial mais rápida, porque o HTML renderizado é menor do que o código JavaScript de todo o aplicativo. React ainda será capaz de reconhecer seu aplicativo e gerenciá-lo após a carga inicial.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The `renderToString()` method is provided on `ReactDOMServer`, which is available here as a global object. The method takes one argument which is a React element. Use this to render `App` to a string.
|
||||
O método `renderToString()` é fornecido em `ReactDOMServer`, que está disponível aqui como um objeto global. O método recebe um argumento que é um elemento React. Use isso para renderizar `App` em uma string.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `App` component should render to a string using `ReactDOMServer.renderToString`.
|
||||
O componente `App` deve renderizar em uma string usando `ReactDOMServer.renderToString`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036171
|
||||
title: Render State in the User Interface
|
||||
title: Renderizar Estado na Interface do Usuário
|
||||
challengeType: 6
|
||||
forumTopicId: 301409
|
||||
dashedName: render-state-in-the-user-interface
|
||||
@ -8,23 +8,23 @@ dashedName: render-state-in-the-user-interface
|
||||
|
||||
# --description--
|
||||
|
||||
Once you define a component's initial state, you can display any part of it in the UI that is rendered. If a component is stateful, it will always have access to the data in `state` in its `render()` method. You can access the data with `this.state`.
|
||||
Uma vez que você define o estado inicial de um componente, você pode exibir qualquer parte dele na interface do usuário que é renderizada. Se um componente é stateful, ele sempre terá acesso aos dados no `state` em seu método `render()`. Você pode acessar os dados com `this.state`.
|
||||
|
||||
If you want to access a state value within the `return` of the render method, you have to enclose the value in curly braces.
|
||||
Se você deseja acessar um valor de estado dentro do `return` do método de renderização, você precisa envolver o valor entre chaves.
|
||||
|
||||
`state` is one of the most powerful features of components in React. It allows you to track important data in your app and render a UI in response to changes in this data. If your data changes, your UI will change. React uses what is called a virtual DOM, to keep track of changes behind the scenes. When state data updates, it triggers a re-render of the components using that data - including child components that received the data as a prop. React updates the actual DOM, but only where necessary. This means you don't have to worry about changing the DOM. You simply declare what the UI should look like.
|
||||
`state` é uma das características mais poderosas dos componentes do React. Ele permite que você rastreie dados importantes no seu aplicativo e renderize uma interface do usuário em resposta a alterações nestes dados. Se os seus dados mudarem, sua interface de usuário será alterada. React usa o que é chamado de um DOM virtual, para acompanhar as mudanças nos bastidores. Quando os dados de state atualiza, ele aciona uma re-renderização dos componentes usando esses dados - incluindo componentes filhos que receberam os dados como uma prop. React atualiza o DOM, mas apenas onde necessário. Isso significa que você não precisa se preocupar em mudar o DOM. Você simplesmente declara como deve ser a interface do usuário.
|
||||
|
||||
Note that if you make a component stateful, no other components are aware of its `state`. Its `state` is completely encapsulated, or local to that component, unless you pass state data to a child component as `props`. This notion of encapsulated `state` is very important because it allows you to write certain logic, then have that logic contained and isolated in one place in your code.
|
||||
Note que se você faz um componente stateful, nenhum outro componente está ciente do seu `state`. Seu `state` é completamente encapsulado, ou local para esse componente, a não ser que você passe dados de estado para um componente filho como `props`. Esta noção de `state` encapsulado é muito importante porque permite que você escreva uma certa lógica, depois, tenha essa lógica contida e isolada num só lugar no seu código.
|
||||
|
||||
# --instructions--
|
||||
|
||||
In the code editor, `MyComponent` is already stateful. Define an `h1` tag in the component's render method which renders the value of `name` from the component's state.
|
||||
No editor de código, `MyComponent` já é stateful. Defina uma tag `h1` no método de renderização do componente que renderiza o valor de `name` no state do componente.
|
||||
|
||||
**Note:** The `h1` should only render the value from `state` and nothing else. In JSX, any code you write with curly braces `{ }` will be treated as JavaScript. So to access the value from `state` just enclose the reference in curly braces.
|
||||
**Nota:** O `h1` deve renderizar apenas o valor de `state` e nada mais. Em JSX, qualquer código que você escrever com chaves `{ }` será tratado como JavaScript. Então para acessar o valor do `state` basta incluir a referência em chaves.
|
||||
|
||||
# --hints--
|
||||
|
||||
`MyComponent` should have a key `name` with value `freeCodeCamp` stored in its state.
|
||||
`MyComponent` deve ter uma chave `name` com o valor `freeCodeCamp` armazenado no seu state.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -33,7 +33,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`MyComponent` should render an `h1` header enclosed in a single `div`.
|
||||
`MyComponent` deve renderizar um título `h1` que está dentro de um único `div`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,7 +43,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The rendered `h1` header should only contain text rendered from the component's state.
|
||||
O título `h1` renderizado deve conter apenas texto renderizado do estado do componente.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
|
Reference in New Issue
Block a user