React:在 React Render 方法中使用高级 JavaScript
由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!
- 欢迎大家,祝大家早上好!今天我们将继续学习 freecodecamp 的课程。在之前的文章中,我们已经讲解了如何使用花括号将 JavaScript 代码插入到 JSX 代码中,以及
{ }如何访问 props、传递 props、访问 state、在代码中插入注释以及设置组件样式。 - 你也可以直接在渲染方法中,在 return 语句之前编写 JavaScript 代码,而无需将其放在花括号内。这是因为此时它还不属于 JSX 代码。
- 我即将展示的代码中包含一个 render 方法,它有一个数组,其中包含 20 个短语来表示答案。按钮点击事件绑定到该
ask方法,因此每次点击按钮时,都会生成一个随机数并将其存储为randomIndexin 状态。我们需要修改第 52 行,并重新赋值const,以便代码每次更新时answer都能随机访问数组的不同索引。possibleAnswers - 代码:
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 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>
);
}
}
- 回答:
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>
);
}
}
Larson, Q., 2019. 前端开发库。[在线] Freecodecamp.org。网址:https://www.freecodecamp.org/learn/front-end-development-libraries/react
文章来源:https://dev.to/rthefounding/react-use-advanced-javascript-in-react-render-method-3hn0