【问题标题】:How to replace href attribute value within JSX in tsx file?如何在 tsx 文件中替换 JSX 中的 href 属性值?
【发布时间】:2021-12-26 08:38:04
【问题描述】:

标签的href的默认值是“https://default.xlsx”,但是我想像这样根据三元运算符更改href的属性值,但是不起作用。我该怎么办? href 中的链接是任意的(https://default.xlsx、https://change.xlsx)。由于我们在 tsx 文件中使用 JSX,因此我们在使用表达式时在大括号之间处理它。

默认“https://default.xlsx”没有变化。

看到在同一个文件中具有相同条件语句( selectedTab === TabLabel[Object.keys(TabType)[0]] )的所有三元运算符都可以工作,通过 .setAttribute() 的方法似乎是错了。

<section>

<a href="https://default.xlsx" className="form-download-btn" download>
       Download Excel File
</a>

{selectedTab === TabLabel[Object.keys(TabType)[0]] 
? document.querySelector('a').setAttribute('href','https://default.xlsx')
: document.querySelector('a').setAttribute('href','https://change.xlsx')}

</section>

【问题讨论】:

    标签: reactjs jsx setattribute tsx queryselector


    【解决方案1】:

    不要在 React 中使用原生 DOM 方法,除非选择根元素,并且没有其他选项。在这种情况下,将&lt;a&gt; 的 JSX 标记更改为在 href 之间交替。

    <section>
    <a
      href={
        selectedTab === TabLabel[Object.keys(TabType)[0]]
        ? 'https://default.xlsx'
        : 'https://change.xlsx'
      }
      className="form-download-btn"
      download
    >
           Download Excel File
    </a>
    </section>
    

    【讨论】:

      最近更新 更多