javascript - How would I add a if..else statement in this code?
问题描述
I am currently creating a quiz using ReactJS but I want to put in a if/else statement when the quiz has been complete, if the person playing the quiz gets a score below 3 I want it to have a sad face, if above 3 then a happy one, how would I put this into my code?
I have tried so far to incorporate the if statement but not having much luck
Result.js
import React from 'react';
const Result = ({ score, playAgain }) => (
<div className="score-board">
<div className="score">You scored {score} / 5 correct answers!</div>
<button className="playBtn" onClick={playAgain}>
Play again!
</button>
</div>
);
export default Result;
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './assets/style.css';
import quizService from './quizService';
import QuestionBox from './components/QuestionBox';
import Result from './components/Result';
class QuizBee extends Component {
state = {
questionBank: [],
score: 0,
responses: 0,
};
getQuestions = () => {
quizService().then((question) => {
this.setState({
questionBank: question,
});
});
};
computeAnswer = (answer, correctAnswer) => {
if (answer == correctAnswer) {
this.setState({
score: this.state.score + 1,
});
}
this.setState({
responses: this.state.responses < 5 ? this.state.responses + 1 : 5,
});
};
playAgain = () => {
this.getQuestions();
this.setState({
score: 0,
responses: 0,
});
};
componentDidMount() {
this.getQuestions();
}
render() {
return (
<div className="container">
<div className="title">QuizBee</div>
{this.state.questionBank.length > 0 &&
this.state.responses < 5 &&
this.state.questionBank.map(({ question, answers, correct, questionId }) => (
<QuestionBox
question={question}
options={answers}
key={questionId}
selected={(answer) => this.computeAnswer(answer, correct)}
/>
))}
{this.state.responses === 5 ? <Result score={this.state.score} playAgain={this.playAgain} /> : null}
</div>
);
}
}
ReactDOM.render(<QuizBee />, document.getElementById('root'));
解决方案
您可以在 Result 组件中执行此操作:
import React from "react";
const Result = ({score, playAgain}) => (
<div className="score-board">
<img src={score <= 3 ? "sad.png" : "happy.png" } /> // <----- HERE
<div className="score">You scored {score} / 5 correct answers!</div>
<button className="playBtn" onClick={playAgain}>
Play again!
</button>
</div>
);
export default Result;
推荐阅读
- dynamics-crm - 当我没有架构实体名称时如何使用获取记录在另一个对象上查找相关记录 - 只是逻辑名称
- jquery - 点击图例动态计算百分比
- c++ - 在 Visual Studio 中从 ctypes 进行远程 DLL 调试
- azure-pipelines - Azure Data Factory send failed notifications to teams channel
- python - 4D 张量形状
- javascript - math.random 总是在数组中返回 1
- javascript - 为什么第二个 Materialise 轮播显示为灰色/不显示?
- laravel - 如何在 Laravel 的关系树中搜索所有关联?
- ios - UIPageViewController 的子视图控制器的生命周期错误
- javascript - @click 事件不会更改 Vue.js 中的数据属性