javascript - 将模板文字作为道具传递不会呈现
问题描述
我有一个功能组件
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]
解决方案
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>`} />
推荐阅读
- libcurl - InternetCrackUrl curl 替代
- swiftui - 使用 'writableContentTypes' Swift 中未包含的内容类型导出文档
- python - NoneType 对象没有使用 item.find 的对象的属性“文本”
- php - 如何在 Codeigniter 的另一个选择查询中添加选择查询
- php - PHP,通过popen执行代码后关闭cmd窗口
- python - 如何在 Windows 中检查正在运行的 shell?
- github - 在 github 上搜索第一个示例
- mysql - 在具有关联的多个表中进行续集插入(具有两个多对多的表)
- r - R:数据帧操作(group_by/aggregate)
- php - Wordpress WooCommerce 'woocommerce_hidden_order_itemmeta' 过滤器挂钩未触发