如何将值从后端传递到 React 前端并在前端的 CSS 中使用该值?

How can I pass a value from the backend to a React frontend and use that value in the CSS for the frontend?

我正在使用 Python 作为我的 React 前端的后端,现在我的后端正在传递 1787 之类的值,我想将该值用作我正在构建的比例的百分比。现在,您可以看到刻度从中间开始:

它不会移动到任何地方,因为后端还没有给它一个数字。但是如果后端给出 23 的分数,三角形将移动到 div 的 23%(黑色边框中勾勒出的):

这是我的 React 前端 HTML 部分中的代码:

<div
  className={
    !this.state.listening
      ? 'results-container'
      : 'results-container-closed'
  }
>
  <div className="result-wrapper">
    {this.state.score === ''
      ? 'Click record and check your score'
      : 'Your Score: ' + this.state.score}
  </div>
</div>

<div className="scale-container">
  <div className="bar">
    <div className="arrow-up"></div>
    <div className="scale-meter"></div>
    <span></span>
  </div>
</div>

this.state.score是我从后端获取分数时存储的地方。

这是我的 CSS:

.arrow-up {
  width: 0; 
  height: 0; 
  border-left: 25px solid transparent;
  border-right: 25px solid transparent;
  text-align: center;
  line-height: 35px;
  position: absolute;
  top: 54px;
  z-index: 1;
  border-bottom: 25px solid purple;

  animation: scale 4s ease;
}

@keyframes scale {
  from {
    left: 48%;
  }
}
.bar:nth-child(1) .arrow-up{
  left: 23%;
}

.bar:nth-child(1) .arrow-up 部分是我希望根据分数更改 left 的地方。有没有一种方法可以让我不用硬编码 left 值,它可以像 left: score%;?

您可以使用内联样式,其中 this.state.score 将是 left 的值 属性:

style={{ left: `${this.state.score}%` }}

您可以使用反引号将 % 字符串与末尾的 score 值连接起来:

<div
  className={
    !this.state.listening
      ? 'results-container'
      : 'results-container-closed'
  }
>
  <div className="result-wrapper">
    {this.state.score === ''
      ? 'Click record and check your score'
      : 'Your Score: ' + this.state.score}
  </div>
</div>

<div className="scale-container">
  <div className="bar">
    <div className="arrow-up" style={{ left: `${this.state.score}%` }}></div>
    <div className="scale-meter"></div>
    <span></span>
  </div>
</div>