如何将锚标记添加到字符串道具?

时间:2019-09-04 18:46:06

标签: javascript reactjs

我有一个可重用的输入/复选框组件,它带有一个label道具:

<Checkbox
  label="I have read and understood the Terms of Service and consent to the Privacy Policy"
/>

和我的复选框的渲染:

<label>
    <input
        type='checkbox'
        disabled={this.props.disabled}
        onChange={this.handleChange}
        checked={this.props.value}
        placeholder={this.props.placeholder}
    />
        {this.label}
</label>

但是我希望标签接受类似

<Checkbox
  label="I have read and understood the <a href="http://....">Terms of Service</a> and consent to the <a href="http://....">Privacy Policy</a>"
/>

,并用单词Terms of ServicePrivacy Policy作为链接。但是,这不起作用。

我是否必须使用类似dangerouslySetInnerHtml的东西才能实现类似的目的?据我了解,使用innerHTML是有风险的吗?

修改我的组件以能够添加这样的链接的最佳方法是什么?

1 个答案:

答案 0 :(得分:4)

您可以传入label道具的JSX而不是字符串,例如:

<Checkbox
  label={
    <>
      I have read and understood the <a href="http://....">Terms of Service</a>{" "}
      and consent to the <a href="http://....">Privacy Policy</a>
    </>
  }
/>;

这是一个完整的例子:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const Checkbox = props => {
  return (
    <label>
      <input
        type="checkbox"
        disabled={props.disabled}
        onChange={props.handleChange}
        checked={props.value}
        placeholder={props.placeholder}
      />
      {props.label}
    </label>
  );
};

function App() {
  return (
    <div className="App">
      <Checkbox
        label={
          <>
            I have read and understood the{" "}
            <a href="http://....">Terms of Service</a> and consent to the{" "}
            <a href="http://....">Privacy Policy</a>
          </>
        }
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

You can view the full interactive example here