将React变量作为属性插入html标签

时间:2019-05-14 15:31:12

标签: html reactjs

我正在尝试获取以下行

<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应该在开始和结束标记之间插入一些东西,而不是在 in 作为标记的属性。

实现该目标的正确JSX语法是什么?

3 个答案:

答案 0 :(得分:2)

首先,您必须确定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'属性。

rendered HTML

演示

您可以继续使用CodeSandbox。
Edit so.answer.56133987

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以这样设置rel

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