简体   繁体   English

动态HTML字符串反应组件

[英]dynamic HTML String to react component

I would be getting dynamic html content from my template rendering which was rendered by other react components. 我将从我的模板渲染中获取动态html内容,该内容由其他反应组件呈现。 How would I convert this html string to React component so that I can use the component in my render function. 我如何将这个html字符串转换为React组件,以便我可以在我的渲染函数中使用该组件。 Note that I want to preserve react specific attributes used for diffing. 请注意,我想保留用于差异的特定反应属性。

 React.createClass( { var self = this; componentWillMountDown : function() { //htmlString is essentially huge dynamic one in my actual case var htmlString = "<div class='classDiv' react-id="0.1"><input type='text'/></div>"; self.setState({responseString : htmlString}); self.forceUpdate(); }, render: function() { var Response = this.state.responseString; //how would I return the react component as response? return (<Response/>); //does not work. err is it shd be valid react component } }); 

I've tried converting htmlString to HTMLDocument object and recursively creating React.createElement in willmount callback and setting react component. 我已经尝试将htmlString转换为HTMLDocument对象,并在willmount回调中递归创建React.createElement并设置react组件。 however, the error is type toUpperCase is not defined. 但是,错误是类型toUpperCase未定义。

A few hours ago, I published an html-to-react module in npm ( https://www.npmjs.com/package/html-to-react ) that may help you. 几个小时前,我在npm( https://www.npmjs.com/package/html-to-react )发布了一个html-to-react模块,可以帮助你。

Please let me know if there's anything you need, I can certainly work with you to make the module more flexible. 如果您有任何需要,请告诉我,我当然可以与您合作,使模块更加灵活。

Because you store your component as string so you have to use dangerouslySetInnerHTML . 因为您将组件存储为字符串,所以您必须使用dangerouslySetInnerHTML This is my suggestion. 这是我的建议。 I hope someone else will have the better answer. 我希望别人能有更好的答案。 :) :)

    render: function() {
    var self = this;
    var Response = React.createClass({
        render: function(){
        return (<div dangerouslySetInnerHTML={{__html: self.state.responseString}}></div>)
        }
    });
    return (
            <Response />
    )
   }

You can use React HTML Parser. 您可以使用React HTML Parser。 Here is the link React HTML Parser 这是链接React HTML Parser

It's a utility for converting HTML strings into React components. 它是一个将HTML字符串转换为React组件的实用程序。 Avoids the use of dangerouslySetInnerHTML and converts standard HTML elements, attributes and inline styles into their React equivalents. 避免使用dangerouslySetInnerHTML并将标准HTML元素,属性和内联样式转换为其React等效项。

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

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