简体   繁体   English

在危险的SetInnerHTML反应组件中使用state

[英]using state in dangerouslySetInnerHTML react component

I have a string about html builded by react.我有一个由反应构建的关于 html 的字符串。 I'm trying to implement render this html string through react, and looking for solution to manage state.我正在尝试通过反应实现渲染这个 html 字符串,并寻找管理 state 的解决方案。

below is simple example.下面是一个简单的例子。

const App = (props) => {
  let code = '<b>Will This Work?</b>';

  return (
    <div dangerouslySetInnerHTML={ {__html: code} }>
    </div>
  );
}

I want to manage the state of component rendered with dangerouslySetInnerHTML option.我想管理使用dangerouslySetInnerHTML选项呈现的组件的 state。

Can i get any ideas about how approach?我可以对如何处理有任何想法吗?

What is dangerouslySetInnerHTML?什么是危险的 SetInnerHTML?

It is a way to set the children of the component (as text/html).这是一种设置组件子项的方法(如 text/html)。

Can state be used in it? state可以用在里面吗?

Yes state can be used with it;是的 state可以和它一起使用; However, the innerHTML MUST be vanilla HTML, NOT JSX.然而,innerHTML 必须是普通的 HTML,而不是 JSX。 An example of this can be seen below: (click the button to change the state from text to a red div)如下所示:(单击按钮将 state 从文本更改为红色 div)

The way this is working is because the state can be inserted into a string literal which will then be handled as HTML encoded text.这是因为 state 可以插入到字符串文字中,然后将其作为 HTML 编码文本处理。

 const App = (props) => { const [state,setState] = React.useState("something I set with state"); let code = `<b>Will This Work? ${state}</b>`; return ( <React.Fragment> <button onClick={()=>{setState("<div style=\"background-color: red; width:50px; height:50px;\"><div>")}}>Click to change state from pure text to an html element</button> <div dangerouslySetInnerHTML={ {__html: code} }> </div> </React.Fragment> ); } ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.querySelector('.react') );
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>

Should you do this?你应该这样做吗?

Probably not.可能不是。 There is a reason it is called dangerouslySetHTML and not safelySetInnerHTML.它被称为危险的SetHTML 而不是safelySetInnerHTML 是有原因的。 See more in the React DocsReact 文档中查看更多信息

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM