首页 > 解决方案 > 根据数组长度显示进度条组件的状态

问题描述

编辑:

我努力了

 <ProgressBar percentage={(percentage / 100) * questions.length} />

但进度没有得到同等更新

我的进度条有一个基本功能组件,如下所示

const ProgressBar = props => {
  const { percentage } = props
  return (
    <div className="progress-bar">
      <Filler percentage={percentage} />
    </div>
  )
}

const Filler = props => {
  const { percentage } = props
  return <div className="filler" style={{ width: `${percentage}%` }} />
}

export default ProgressBar

我像这样导入到主要组件中

this.state = {
      percentage: 0,
    }

我的进度条的状态是通过手柄点击功能更新的

selectAnswer = answer => {
    this.setState(state => ({
      percentage: state.percentage + 20,
      currentQuestionId: state.currentQuestionId + 1,
    }))
  }

我的进度条现在功能齐全,每次用户转到下一个问题时,状态都会更新。

我希望动态更新进度条的状态,根据数组显示其当前状态..

questions object
    0: {id: 1, text: "What is your favourite number?", type: "multiChoice", choices: Array(3)}
    1: {id: 2, text: "What is your favourite colour?", type: "multiChoice", choices: Array(3)}
    2: {id: 3, text: "Which workshop would you prefer?", type: "cardChoice", choices: Array(2)}
    3: {id: 4, text: "Rank your favourite movie from Top to Bottom", type: "rankChoice", choices: Array(5)}
    4: {id: 5, text: "The end.", type: "end"}

例如,如果 currentQuestionId === 2 ,this.state.percentage 将反映这一点,或者如果 currentQuestionId === 5,则此 state.percentage 将是 100

标签: javascriptreactjsoopecmascript-6

解决方案


推荐阅读