【问题标题】:How can I render a SVG based on ternary operator inside a JSX?如何在 JSX 中渲染基于三元运算符的 SVG?
【发布时间】:2023-01-17 19:00:51
【问题描述】:

我使用的是 Stencil.js,但语法类似于 React。

const iconSVG = <svg>...</svg>

return (
      <button>
      {this.icon ?
       this.position === 'left'
        ? iconSVG `${this.label}`
        : `${this.label} icon` 
      : this.label}
      </button>
    );

这给了我一个错误:iconSVG is not a function

return (
      <button>
      {this.icon ?
       this.position === 'left'
        ? <svg> ...</svg> `${this.label}`
        : `${this.label} icon` 
      : this.label}
      </button>
    );

由于this.label,这不起作用。只能有一个元素(值)。

 return (
          <button>
          {this.icon ?
           this.position === 'left'
            ? `${<svg> ...</svg>} `${this.label}`
            : `${this.label} icon` 
          : this.label}
          </button>
        );

这让我在 label 旁边的 Button 内得到了 [Object object]

const iconSVG = () => <svg> ...</svg>

return (
      <button>
      {this.icon ?
       this.position === 'left'
        ? iconSVG() `${this.label}`
        : `${this.label} icon` 
      : this.label}
      </button>
    );

这给了我一个错误:iconSVG(...) is not a function 显然是因为首先读取了 JSX。

那么,我该怎么做呢?如何在 JSX 中渲染 SVG

【问题讨论】:

    标签: reactjs svg jsx stenciljs


    【解决方案1】:

    使用您的 svg 如下。

    export const IconSvg = () => {
      return (
          <svg>
            ...
          </svg>
      );
    };
    

    然后 , 与您的三元运算符一起使用。

    例如。

    import React from "react";
    
    const isRed = true;
    
    export const RedIconSvg = () => {
      return (
          <svg width="100" height="100">
            <circle cx="50" cy="50" r="40" fill="red" />
          </svg>
      );
    };
    
    export const BlueIconSvg = () => {
      return (
          <svg width="100" height="100">
            <circle cx="50" cy="50" r="40" fill="blue" />
          </svg>
      );
    };
    
    function App() {
      return (
        <div className="App">
          {isRed ? <RedIconSvg/> : <BlueIconSvg/>}
        </div>
      );
    }
    
    export default App;
    

    【讨论】:

    • 你从哪里导出这个函数,你如何在三元运算符中使用它?
    • 请再次检查我的回答。我给你写了一个例子。
    • 你的 JSX 中的 this.label 在哪里?您正在渲染单个 svg 组件,但我正在渲染两个项目!我需要 svg 旁边的 this.label
    • this.lable 的价值是多少?您也可以在我的 svg 组件中渲染。你明白了吗?如果您不知道该怎么做,请告诉我。
    • this.label 的值作为 prop 传递。不管它是什么。它必须在那里。你不能把它放在 svg 中。
    【解决方案2】:

    你可以试试 :

    return (
        <button>
            {this.icon && this.position === 'left' && <svg>...</svg>}
            {this.label}
            {this.icon && this.position !== 'left' && ' icon'}
        </button>
    );
    
    

    【讨论】:

    • 是的,这可行,但这是唯一的解决方案吗?我不喜欢重复的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2022-01-04
    • 2014-11-27
    • 1970-01-01
    相关资源
    最近更新 更多