简体   繁体   English

如何使用 React+Typescript 有条件地内联样式组件?

[英]How to inline style components conditionally using React+Typescript?

I have a an anchor component that I would like to style conditionally:我有一个锚组件,我想有条件地设置样式:

<a
  className="menu-item"
  role="button"
  href="/#"
  style={renderChangeColor}
>
  {changeStr}
</a>



const renderChangeColor = () => {
    let style = {};
    if (changeSign === POSITIVE) {
      style["color"] = "green";
    } else if (changeSign === NEGATIVE) {
      style["color"] = "red";
    } else {
      style["color"] = "white";
    }
    return style;
  };

However, when I try to compile, it throws an error:但是,当我尝试编译时,它会引发错误:

TypeScript error in /Users/coinflex/coinflex/markets/src/components/Trade/MarketOverview/AssetSelector/AssetSelectorRow/AssetSelectorRow.tsx(32,7):
Element implicitly has an 'any' type because expression of type '"color"' can't be used to index type '{}'.
  Property 'color' does not exist on type '{}'.  TS7053

    30 |     let style = {};
    31 |     if (changeSign === POSITIVE) {
  > 32 |       style["color"] = "green";
       |       ^
    33 |     } else if (changeSign === NEGATIVE) {
    34 |       style["color"] = "red";
    35 |     } else {

you need to add a type to style, because otherwise, it is implicit any , and since your initial object isn't have a value, color is optional (for this reason I use ? )您需要为样式添加一个类型,否则它是implicit any ,并且由于您的初始 object 没有值,因此颜色是可选的(因此我使用?

 const renderChangeColor = () => { let style: { color?: string } = {}; // with the type, style isn't any. if (changeSign === POSITIVE) { style["color"] = "green"; } else if (changeSign === NEGATIVE) { style["color"] = "red"; } else { style["color"] = "white"; } return style; };

You will need to add types and call the function renderChangeColor (not just provide reference)您将需要添加类型并调用 function renderChangeColor (不仅仅是提供参考)

Style fix样式修复

const renderChangeColor = () => {
  let style:React.CSSProperties = {}; //<---------------- type fix
  if (changeSign === POSITIVE) {
    style["color"] = "green";
  } else if (changeSign === NEGATIVE) {
    style["color"] = "red";
  } else {
    style["color"] = "white";
  }
  return style;
};

Tsx fix Tsx 修复

      <a
        className="menu-item"
        role="button"
        href="/#"
        style={renderChangeColor()} //<------------ call the function
      >
        {changeStr}
      </a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM