首页 > 解决方案 > 将模板文字作为道具传递不会呈现

问题描述

我有一个功能组件

const Paragraph = forwardRef((ref: any) => {
  return (
    <div>
      <p dangerouslySetInnerHTML={{ __html: props.text }}></p>
    </div>
  );
});

当我调用这个组件时,我无法呈现这个模板文字:

<Paragraph text={`${<a href="#">Terms of Service</a>} and ${<a href="#">Privacy Policy</a>}`} />

结果是: [object Object] and [object Object]

标签: javascriptreactjstemplate-strings

解决方案


ES6 模板文字将表达式${}转换为字符串。你给它的 JSX 对象${<a href="#">Terms of Service</a>}不能真正转换为字符串表示,它所能做的最好的就是[object Object].

您真正想要的是将内部 HTML 设置为实际的 string <a href="#">Terms of Service</a>,因此只需删除${}标签周围的标签即可获得预期的结果。

<Paragraph text={`<a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a>`} />

推荐阅读