2021-06-15 00:49:18 -07:00
---
id: 5a24c314108439a4d4036183
2021-07-30 23:57:21 +09:00
title: Usar JavaScript avançado no método de renderização do React
2021-06-15 00:49:18 -07:00
challengeType: 6
forumTopicId: 301415
dashedName: use-advanced-javascript-in-react-render-method
---
# --description--
2021-07-30 23:57:21 +09:00
Nos desafios anteriores, você aprendeu como injetar o código JavaScript em JSX usando chaves `{ }` para tarefas como acessar props, passar props, acessar o state, inserir comentários em seu código e, mais recentemente, estilizar seus componentes. Estes são todos os casos de uso comuns para colocar JavaScript em JSX, mas eles não são a única maneira de você usar o código JavaScript em seus componentes do React.
2021-06-15 00:49:18 -07:00
2021-07-30 23:57:21 +09:00
Você também pode escrever JavaScript diretamente nos seus métodos de `render` , antes da instrução `return` , ** *sem*** inseri-lo dentro de chaves. Isto é devido a ainda não estar dentro do código JSX. Quando você quiser usar uma variável mais tarde no código JSX *dentro* da instrução `return` , você coloca o nome da variável dentro de chaves.
2021-06-15 00:49:18 -07:00
# --instructions--
2021-07-30 23:57:21 +09:00
No código fornecido, o método `render` tem um array que contém 20 frases para representar as respostas encontradas no clássico brinquedo da Bola Mágica de 1980. O evento de clique no botão está ligado ao método `ask` , então cada vez que o botão é clicado um número aleatório será gerado e armazenado como o `randomIndex` no state. Na linha 52, exclua a string `change me!` e reatribua a const `answer` para que seu código acesse aleatoriamente um índice diferente do array `possibleAnswers` a cada vez que o componente atualizar. Finalmente, insira a const `answer` dentro das tags `p` .
2021-06-15 00:49:18 -07:00
# --hints--
2021-07-26 23:39:21 +09:00
O componente `MagicEightBall` deve existir e deve renderizar à página.
2021-06-15 00:49:18 -07:00
2021-07-26 23:39:21 +09:00
```js
assert.strictEqual(
2021-06-15 00:49:18 -07:00
Enzyme.mount(React.createElement(MagicEightBall)).find('MagicEightBall')
.length,
1
);
2021-07-26 23:39:21 +09:00
```
2021-06-15 00:49:18 -07:00
2021-07-19 16:05:37 +05:30
O primeiro filho de `MagicEightBall` deve ser um elemento `input` .
2021-06-15 00:49:18 -07:00
```js
assert.strictEqual(
Enzyme.mount(React.createElement(MagicEightBall))
.children()
.childAt(0)
.name(),
'input'
);
```
2021-07-19 16:05:37 +05:30
O terceiro filho de `MagicEightBall` deve ser um elemento `button` .
2021-06-15 00:49:18 -07:00
```js
assert.strictEqual(
Enzyme.mount(React.createElement(MagicEightBall))
.children()
.childAt(2)
.name(),
'button'
);
```
2021-07-30 23:57:21 +09:00
`MagicEightBall` deve ser inicializado com uma propriedade `userInput` e uma propriedade `randomIndex` ambas definidas com o valor de uma string vazia.
2021-06-15 00:49:18 -07:00
```js
assert(
Enzyme.mount(React.createElement(MagicEightBall)).state('randomIndex') ===
'' & &
Enzyme.mount(React.createElement(MagicEightBall)).state('userInput') === ''
);
```
2021-07-19 16:05:37 +05:30
Quando `MagicEightBall` for montado pela primeira vez no DOM, ele deve retornar um elemento `p` vazio.
2021-06-15 00:49:18 -07:00
```js
assert(
Enzyme.mount(React.createElement(MagicEightBall)).find('p').length === 1 & &
Enzyme.mount(React.createElement(MagicEightBall)).find('p').text() === ''
);
```
2021-07-19 16:05:37 +05:30
Quando o texto é inserido no elemento `input` e o botão é clicado, o componente `MagicEightBall` deve retornar um elemento `p` que contém um elemento aleatório do array `possibleAnswers` .
2021-06-15 00:49:18 -07:00
```js
(() => {
const comp = Enzyme.mount(React.createElement(MagicEightBall));
const simulate = () => {
comp.find('input').simulate('change', { target: { value: 'test?' } });
comp.find('button').simulate('click');
};
const result = () => comp.find('p').text();
const _1 = () => {
simulate();
return result();
};
const _2 = () => {
simulate();
return result();
};
const _3 = () => {
simulate();
return result();
};
const _4 = () => {
simulate();
return result();
};
const _5 = () => {
simulate();
return result();
};
const _6 = () => {
simulate();
return result();
};
const _7 = () => {
simulate();
return result();
};
const _8 = () => {
simulate();
return result();
};
const _9 = () => {
simulate();
return result();
};
const _10 = () => {
simulate();
return result();
};
const _1_val = _1();
const _2_val = _2();
const _3_val = _3();
const _4_val = _4();
const _5_val = _5();
const _6_val = _6();
const _7_val = _7();
const _8_val = _8();
const _9_val = _9();
const _10_val = _10();
const actualAnswers = [
_1_val,
_2_val,
_3_val,
_4_val,
_5_val,
_6_val,
_7_val,
_8_val,
_9_val,
_10_val
];
const hasIndex = actualAnswers.filter(
(answer, i) => possibleAnswers.indexOf(answer) !== -1
);
const notAllEqual = new Set(actualAnswers);
assert(notAllEqual.size > 1 & & hasIndex.length === 10);
})();
```
# --seed--
## --after-user-code--
```jsx
var possibleAnswers = [
'It is certain',
'It is decidedly so',
'Without a doubt',
'Yes, definitely',
'You may rely on it',
'As I see it, yes',
'Outlook good',
'Yes',
'Signs point to yes',
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
"Don't count on it",
'My reply is no',
'My sources say no',
'Outlook not so good',
'Very doubtful',
'Most likely'
];
ReactDOM.render(< MagicEightBall / > , document.getElementById('root'));
```
## --seed-contents--
```jsx
const inputStyle = {
width: 235,
margin: 5
};
class MagicEightBall extends React.Component {
constructor(props) {
super(props);
this.state = {
userInput: '',
randomIndex: ''
};
this.ask = this.ask.bind(this);
this.handleChange = this.handleChange.bind(this);
}
ask() {
if (this.state.userInput) {
this.setState({
randomIndex: Math.floor(Math.random() * 20),
userInput: ''
});
}
}
handleChange(event) {
this.setState({
userInput: event.target.value
});
}
render() {
const possibleAnswers = [
'It is certain',
'It is decidedly so',
'Without a doubt',
'Yes, definitely',
'You may rely on it',
'As I see it, yes',
'Outlook good',
'Yes',
'Signs point to yes',
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
"Don't count on it",
'My reply is no',
'My sources say no',
'Most likely',
'Outlook not so good',
'Very doubtful'
];
const answer = 'change me!'; // Change this line
return (
< div >
< input
type='text'
value={this.state.userInput}
onChange={this.handleChange}
style={inputStyle}
/>
< br / >
< button onClick = {this.ask} > Ask the Magic Eight Ball!< / button >
< br / >
< h3 > Answer:< / h3 >
< p >
{/* Change code below this line */}
{/* Change code above this line */}
< / p >
< / div >
);
}
}
```
# --solutions--
```jsx
const inputStyle = {
width: 235,
margin: 5
};
class MagicEightBall extends React.Component {
constructor(props) {
super(props);
this.state = {
userInput: '',
randomIndex: ''
};
this.ask = this.ask.bind(this);
this.handleChange = this.handleChange.bind(this);
}
ask() {
if (this.state.userInput) {
this.setState({
randomIndex: Math.floor(Math.random() * 20),
userInput: ''
});
}
}
handleChange(event) {
this.setState({
userInput: event.target.value
});
}
render() {
const possibleAnswers = [
'It is certain',
'It is decidedly so',
'Without a doubt',
'Yes, definitely',
'You may rely on it',
'As I see it, yes',
'Outlook good',
'Yes',
'Signs point to yes',
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
"Don't count on it",
'My reply is no',
'My sources say no',
'Outlook not so good',
'Very doubtful',
'Most likely'
];
const answer = possibleAnswers[this.state.randomIndex];
return (
< div >
< input
type='text'
value={this.state.userInput}
onChange={this.handleChange}
style={inputStyle}
/>
< br / >
< button onClick = {this.ask} > Ask the Magic Eight Ball!< / button >
< br / >
< h3 > Answer:< / h3 >
< p > {answer}< / p >
< / div >
);
}
}
```