React中的内联样式(进度栏进度)

时间:2019-02-23 01:34:12

标签: css reactjs progress-bar styling

我正在尝试使用className“ progress”设置元素的样式,即使尝试了无数种可能性,我也无法终生解决。

我将得到的任何帮助或提示将不胜感激!这是组件的代码:

  constructor(props) {
    super(props);

    this.state = {
      arrIterator: 0,
      counter: 0,
      sets: props.ids.sets,
      exercises: props.program,
      ids: props.ids
    }

    // Helper variable to decide when a new round starts --> Reset counter
    this.newRoundOn = ((this.state.exercises.length /this.state.sets) -1);

    // Gets percentage for progressbar
    let barPercentage = ((this.state.arrIterator / this.state.exercises.length) * 100) +"%";

    this.style = {
      width: {barPercentage} 
    }
  }

  // Renders Progress Bar
  renderProgressBar() {
    return(
      <div className="card-panel" id="progresjon-panel">
      <div className="row">
          <h5 className="col s8">Progresjon</h5>
          <h5 className="col s4 right-align">{this.state.arrIterator +1} / {this.state.exercises.length}</h5>
      </div>
      <div className="progress" style={style}>
          <div className="determinate"></div>
      </div>
  </div>
    );
  }

2 个答案:

答案 0 :(得分:0)

您必须修改状态才能使进度条更改其值。使用componentDidUpdate方法检查某些属性是否已更改,然后设置新的barPercentage值:

作为一个小建议,您应该避免使用passing props to state

constructor () {
   this.state = {
     barPercentage: 0
   } 
}

componentDidUpdate (prevProps) {
  // Helper variable to decide when a new round starts --> Reset counter
  this.newRoundOn = ((this.props.exercises.length /this.props.sets) -1);

  // Gets percentage for progressbar
  let barPercentage = (this.props.arrIterator / this.props.exercises.length) * 100;

  if (this.props.arrIterator > prevProps.arrIterator) {
    this.setState({ barPercentage })
  }
}

render () {
  return (
    // [...]
    <div className="progress" style={{ width: `${this.state.barPercentage}%` }}>
      <div className="determinate"></div>
    </div>
    // [...]
  )
}

答案 1 :(得分:0)

  constructor(props) {
    super(props);

    this.state = {
      arrIterator: 0,
      counter: 0,
      sets: props.ids.sets,
      exercises: props.program,
      ids: props.ids
    }

    // Helper variable to decide when a new round starts --> Reset counter
    this.newRoundOn = ((this.state.exercises.length /this.state.sets) -1);

    // Gets percentage for progressbar
    let barPercentage = ((this.state.arrIterator / this.state.exercises.length) * 100) +"%";

    this.style = {
      width: {barPercentage} 
    }
  }

  // Renders Progress Bar
  renderProgressBar() {
    return(
      <div className="card-panel" id="progresjon-panel">
      <div className="row">
          <h5 className="col s8">Progresjon</h5>
          <h5 className="col s4 right-align">{this.state.arrIterator +1} / {this.state.exercises.length}</h5>
      </div>
      <div className="progress" style={style}>
          <div className="determinate"></div>
      </div>
  </div>
    );
  }