【问题标题】:Insert React variable as attribute in html tag在 html 标签中插入 React 变量作为属性
【发布时间】:2019-10-01 16:35:42
【问题描述】:

我正在尝试获取以下行

<a href="/users/users/authentication" rel='nofollow'>

注意 rel='nofollow'

在我的 React 组件的 render 方法中,我有这个 JSX 语法:

render() {
  const rel = "rel='nofollow'";
  return (
    <div>
      <a href="/users/users/authentication" {rel}>
    </div>
  );
}

我得到一个: 错误:/~/Scripts/Navigation.jsx:意外的令牌,应为“...”

我也试过

let rel = { __html: "<b>Hey</b>" };

<a href="/users/users/authentication" dangerouslySetInnerHTML={rel}>

也失败了,但无论如何,SetInnerHTML 应该在开始和结束标记之间注入一些东西,而不是 within 作为标记的属性。

实现这一点的正确 JSX 语法是什么?

【问题讨论】:

  • 你不必改变任何关于 HTML 语法的东西来设置 React 中的基本属性,除非它是一个多词属性,在某些情况下是驼峰式。但只需输入&lt;a href="/users/users/authentication" rel='nofollow'&gt; 就可以了。
  • 我相信这正是您正在寻找的stackoverflow.com/questions/38619182/…

标签: html reactjs


【解决方案1】:

您首先必须决定rel 值的“形状”应该是什么。会是文字吗?或者它会是一个对象?

1 rel 是一个文本。

如果rel 作为原始文本传递,例如nofollow,您必须手动分配rel 属性。

function LinkWithPropertyAssignment() {
  const rel = "nofollow";

  return (
    <a href="https://www.google.com" rel={rel}>
      Google
    </a>
  );
}

2 rel 是一个对象。

如果 rel 作为对象传递,例如 {rel: 'nofollow'},那么您可以简单地将对象传递给锚元素。

function LinkWithObjectSpread() {
  const rel = { rel: "nofollow" };

  return (
    <a href="https://www.bing.com" {...rel}>
      Bing
    </a>
  );
}

可以看到两者都会添加rel='nofollow'属性。

演示

您可以关注 CodeSandbox。

【讨论】:

    【解决方案2】:
      render() {
      const theRel = "nofollow";
      return (
        <div>
          <a href="/users/users/authentication" rel={theRel}/>
        </div>
      );
    }
    

    【讨论】:

      【解决方案3】:

      你可以这样设置rel

      render() {
        const rel = "nofollow";
        return (
          <div>
            <a href="/users/users/authentication" rel={rel}>Hey</a>
          </div>
        );
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 2018-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多