Javascript 如何使用 html 字符串呈现 React 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29706828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:49:42  来源:igfitidea点击:

How to render a react element using an html string?

javascriptreactjs

提问by Derek

var Klass = React.createClass({
  this.props.html_string = '<button>BUTTON_TEXT</button>';
  render: function(){
    return (
      <div className="wrapper">
        {this.props.html_string}
      </div>
    );
  }
});

Currently {this.props.html_string}gives me a text node. How can I make this a HTML DOM node?

目前{this.props.html_string}给了我一个文本节点。我怎样才能使它成为一个 HTML DOM 节点?

回答by SnareHanger

What you want is dangerouslySetInnerHTML

你想要的是 dangerouslySetInnerHTML

https://facebook.github.io/react/tips/dangerously-set-inner-html.html

https://facebook.github.io/react/tips/dangerously-set-inner-html.html

function createMarkup() { return {__html: 'First &middot; Second'}; };
<div dangerouslySetInnerHTML={createMarkup()} />

Edit:you'll want to htmlencode the string.

编辑:您需要对字符串进行 htmlencode。

回答by Kosmetika

Also be aware of React.renderToString('html')which can be used on server - https://facebook.github.io/react/docs/top-level-api.html

还要注意React.renderToString('html')哪些可以在服务器上使用 - https://facebook.github.io/react/docs/top-level-api.html