React 组件:"if else" 语句未在 return 语句内更新

React Component : "if else" statement not updating inside return statement

我是 React 的菜鸟,在前面还很新。

我正在尝试在 React 中更改 属性 "fill"(多边形)的颜色。 如果 perc > 50 我希望结果为绿色,否则为红色。

我已经写了一个 "if else" 语句但是没有颜色渲染。

我已经检查了这个 和其他在线来源/我想做的似乎是可行的,但我不知道为什么它没有呈现。

import React, { Component } from 'react';

class SvgStationIconGauge extends Component {
  render() {
    const { perc } = this.props || 0;
    const color_fill = 0;
    if (perc >50) {
      color_fill = "#ff0000";
    } else {
      color_fill = "#00ff00";
    }
    return (
      <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 50 120" className="icon-station">
        <title>Station name</title>
        <desc>Marker with gauge to display availability </desc>
     //#Here is what i am trying to render!!
        <polygon points="2 2 48 2 48 80 25 118 2 80" stroke="#333333" strokeWidth="4" fill= {color_fill} />
        <clipPath id="fill-icon">
          <polygon points="4 4 46 4 46 80 25 116 4 80 " strokeWidth="1" />
        </clipPath>
        <g clipPath="url(#fill-icon)">
          <rect width="100%" height={perc} fill="white" />
        </g>
      </svg>
    );
  }
}

export default SvgStationIconGauge;

如前所述,我是 React 的菜鸟,欢迎任何意见或建议!

你不能辞职 const。使用 let

let color_fill = 0;
    if (perc >50) {
      color_fill = "#ff0000";
    } else {
      color_fill = "#00ff00";
    }

您不能重新分配 const 值。将 colour_fill 设为 let 或尝试:

const color_fill = perc >50 ? "#ff0000" : "#00ff00";