You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React测验应用实现多变量分数递增的技术方案咨询

实现按题目自定义分值的计分逻辑

没问题,这需求很好实现!核心思路就是给每个题目添加专属的分值字段,然后在判断答案正确时,累加对应题目分值而非固定的1分。咱们一步步来改:

第一步:给题库添加分值字段

首先修改你的qBank,给每个题目对象新增points属性,设置你想要的自定义分值:

let qBank = [ 
  { 
    question: "I plan to begin withdrawing money from my investments in:", 
    options: ["Less than 3 years", "3-5 years", "6-10 years", "11 years or more"], 
    answer:"3-5 years", 
    id:"0",
    points: 3 // 自定义该题分值
  }, 
  { 
    question: "Once I begin withdrawing funds from my investments, I plan to spend all of the funds in:", 
    options: ["Less than 2 years", "2-5 years", "6-10 years", "11 years or more"], 
    answer:"2-5 years", 
    id:"1",
    points: 4 // 自定义该题分值
  }, 
  { 
    question: "I would describe my knowledge of investments as:", 
    options: ["None", "Limited", "Good", "Extensive"], 
    answer:"None", 
    id:"2",
    points: 2 // 自定义该题分值
  } 
]

第二步:修改计分逻辑

接下来调整nextQuestionHandler里的计分代码,把固定加1改成动态获取当前题目的points值累加:

nextQuestionHandler = () => { 
  const { userAnswer, answers, score, currentQuestion } = this.state; 
  
  // 先判断答案是否正确,正确则累加当前题目的对应分值
  if (userAnswer === answers) { 
    this.setState({ score: score + qBank[currentQuestion].points }) 
  } 
  
  // 再切换到下一题
  this.setState({ currentQuestion: this.state.currentQuestion + 1 }) 
}

小提醒:我把计分逻辑放到了切换题目之前,这样能确保我们取到的是当前正在作答的题目的分值,而不是切换后的新题目,避免逻辑错误。

第三步:确认组件更新逻辑

你的componentDidUpdate逻辑不需要改动,它会正常加载下一题的所有内容;如果之后需要在页面上显示当前题目的分值,直接从qBank[currentQuestion].points里取值渲染即可。

这样改完之后,用户答对不同题目就会获得对应的自定义分值啦!

内容的提问来源于stack exchange,提问作者PinkFloyd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:32:31