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

Spa*_*000 3 javascript reactjs

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

<Checkbox
  label="I have read and understood the Terms of Service and consent to the Privacy Policy"
/>
Run Code Online (Sandbox Code Playgroud)

和我的复选框的渲染:

<label>
    <input
        type='checkbox'
        disabled={this.props.disabled}
        onChange={this.handleChange}
        checked={this.props.value}
        placeholder={this.props.placeholder}
    />
        {this.label}
</label>
Run Code Online (Sandbox Code Playgroud)

但是我希望标签接受类似的东西

<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>"
/>
Run Code Online (Sandbox Code Playgroud)

并有文字Terms of ServicePrivacy Policy链接。然而这行不通。

我是否必须使用类似的东西dangerouslySetInnerHtml来实现这样的目标?从我理解使用innerHTML是一种风险,不是吗?

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

sko*_*ovy 5

您可以为labelprop传入 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>
    </>
  }
/>;

Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子:

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);
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看完整的交互式示例