简体   繁体   English

在React中危险地渲染带有JSX表达式的HTML字符串SetInnerHTML()

[英]Render HTML string w/JSX expression in React dangerouslySetInnerHTML()

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. 我已经成功地使用了React的angerousedSetInnerHTML来呈现我从API获得的HTML字符串响应,但是现在我需要将单击处理程序添加到由hazardallySetInnerHTML设置的某些响应的一部分中。 Is there a way to add handlers to dangerouslySetInnerHTML conent? 有没有一种方法可以将处理程序添加到dragonallySetInnerHTML内容中? Example: 例:

var api_response = '<a onClick={this.props.methodName} href="www.google.com">example</a>';

return <div dangerouslySetInnerHTML={_markupFromString(api_response)}></div>

function _markupFromString (msg) {
    return { '__html': msg };
}

This isn't going to work. 这行不通。 dangerouslySetInnerHTML() doesn't work with JSX. 危险地,SetInnerHTML()无法与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. 更好的策略是让AJAX调用简单地返回所需的字符串和(链接和标题),并提供具有这些值的组件作为道具。 The component is simply the link in this situation. 在这种情况下,组件只是链接。

Or you can add your SVG in the file public/index.html then create In your component a function like this 或者,您可以将SVG添加到文件public / index.html中,然后在组件中创建一个如下所示的函数

doSomething() {
 console.log('ajajaj');
}

componentDidMount() {
 window.NameVarible =  this.doSomething;
}

And add your event onClick="NameVariable()" in the SVG 并在SVG中添加事件onClick="NameVariable()"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Render HTML代码(dangerouslySetInnerHTML?) - React Render HTML Code (dangerouslySetInnerHTML?) 反应使用危险的SetInnerHTML 渲染带有 html 标签的 json - react use dangerouslySetInnerHTML to render json with html tags 是否可以在不使用 dangerouslySetInnerHtml 的情况下渲染 HTML - Is it possible to render HTML in react without using dangerouslySetInnerHtml 如何在 React 中使用危险的 SetInnerHTML 解析 Jsx 字符串? - How to parse Jsx String with expressions using dangerouslySetInnerHTML in React? 设置危险地设置innerHtml时,如何从ReactJS中的html字符串呈现react组件? - How to render a react component from html string in ReactJS while setting in dangerouslysetinnerHtml? 用React.js组件替换部分html字符串并渲染(没有dangerouslySetInnerHTML) - Replace part of html string with React.js component and render (without dangerouslySetInnerHTML) 反应 | 在 jsx 中渲染 html 标签 - React | render html tag in jsx React 使用预先确定的组件在字符串上添加 HTML 标签(替代危险的SetInnerHTML) - React add HTML tags on string using predetermined components (alternative to dangerouslySetInnerHTML ) 如何在 React jsx 中呈现 object 值 Html? - How to render an object value that is Html in react jsx? 在反应绑定中渲染包含 JSX 的字符串 - Render string containing JSX in react binding
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM