jsx渲染html字符串,渲染HTML字符串w/JSX表达式在发生危险的setinnerhtml ()

本文介绍如何在React中安全地使用dangerouslySetInnerHTML来渲染API返回的HTML字符串,并探讨了为通过dangerouslySetInnerHTML渲染的内容添加点击事件处理程序的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have successfully used React's dangerouslySetInnerHTML to render HTML string responses I'm getting from an API, but now I need to add a click handler to parts of certain responses that are set by dangerouslySetInnerHTML. Is there a way to add handlers to dangerouslySetInnerHTML conent? Example:

我已经成功地使用了React的危险的setinnerhtml来呈现我从一个API中得到的HTML字符串响应,但是现在我需要添加一个click处理程序到一些由危险的lysetinnerhtml设置的响应中。是否有一种方法可以将处理程序添加到危险的setinnerhtml中?例子:

var api_response = 'example';

return

function _markupFromString (msg) {

return { '__html': msg };

}

2 个解决方案

#1

0

This isn't going to work. dangerouslySetInnerHTML() doesn't work with JSX. A better strategy would be to have the AJAX call simply return the required strings and (link and title) and supply a component with these values as props. The component is simply the link in this situation.

这行不通。setinnerhtml()与JSX不兼容。更好的策略是让AJAX调用简单地返回所需的字符串(链接和标题),并以这些值作为道具提供一个组件。组件只是这种情况下的链接。

#2

0

Or you can add your SVG in the file public/index.html then create In your component a function like this

或者可以在文件public/index中添加SVG。然后在组件中创建一个这样的函数。

doSomething() {

console.log('ajajaj');

}

componentDidMount() {

window.NameVarible = this.doSomething;

}

And add your event onClick="NameVariable()" in the SVG

在SVG中添加事件onClick="NameVariable()"。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值