【发布时间】:2020-02-19 03:08:18
【问题描述】:
使用 React,我创建了一个测验,用户可以在其中提出问题并选择答案: https://codesandbox.io/s/quiz-1cf1m
我正在尝试添加书签功能,用户可以在其中“添加书签”他们想要稍后返回的问题。测验结束后,可以在结果摘要中显示他们收藏的问题列表(并希望单击以获取该特定问题)。
在我的问题组件中,我添加了 isBookMarked 设置为 false 和 bookmarkedQuestions 设置为一个空数组。然后创建了一个切换书签图标的 handleBookmark 函数。
class Question extends React.Component {
state = {
pick: false,
correct: false,
isBookmarked: false,
bookmarkedQuestions: []
};
correctOrIncorrect = pick => {
if (pick === this.state.pick) {
return this.state.correct ? "correct" : "incorrect";
} else if (
pick === !this.state.correct &&
this.props.currentQuestion.correctAnswer
) {
return "correct";
} else {
return "clear";
}
};
handleSelect = pick => {
if (pick === this.props.currentQuestion.correctAnswer) {
this.setState({ pick, correct: true });
} else {
this.setState({ pick });
}
};
moveToNextQuestion = () => {
this.setState({ pick: false, correct: false });
this.props.nextQuestionHandler(this.state.correct);
};
handleBookmark = () => {
console.log(this.props.currentQuestion);
this.setState({
isBookmarked: !this.state.isBookmarked
});
};
render() {
const { currentQuestion, shuffledAnswerChoices } = this.props;
return (
<div className={this.props.animation ? this.props.animation : null}>
<span>
<i
id={currentQuestion}
className={
this.state.isBookmarked ? "fa fa-bookmark" : "fa fa-bookmark-o"
}
onClick={() => this.handleBookmark()}
/>
</span>
<p>{currentQuestion.text}</p>
<ol type="A">
{shuffledAnswerChoices.map((pick, idx) => {
return (
<li
key={idx}
className={this.state.pick ? this.correctOrIncorrect(pick) : null}
onClick={() => this.handleSelect(pick)}
>
{pick}
</li>
);
})}
</ol>
{this.state.pick && (
<div>
{this.state.correct ? (
<p>
<i>Correct!</i>
</p>
) : (
<p>
<i>Incorrect</i>
</p>
)}
<button className="next-btn" onClick={this.moveToNextQuestion}>
Next
</button>
</div>
)}
</div>
);
}
}
export default Question;
我意识到使用当前的代码,当我为该图标添加书签时,除非我再次单击以取消添加书签,否则该图标会在整个测验过程中保持为书签。我添加了一个控制台日志,并且可以获取我正在处理的当前问题。我坚持只能为选定的问题添加书签,一旦用户转到下一个问题,它就会“重置”。我还尝试在添加书签时将问题推送到空的 bookmarkedQuestions 数组中,我想在测验结束时显示该数组(但刚刚意识到结果组件是同级而不是问题组件的子级,因此不能作为道具传下去……)。
那里有任何 React Pros 可以教我如何解决这个问题...?
从此书签系统扩展的附加问题:关于如何再次重复所有不正确的问题直到所有问题都得到正确回答的任何方法建议,摘要显示第一次正确回答了多少问题?
【问题讨论】:
标签: javascript reactjs frontend