React:在危险的SetInnerHTML 中使用React 组件 [英] React: using React component inside of dangerouslySetInnerHTML

查看:70
本文介绍了React:在危险的SetInnerHTML 中使用React 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用 React 的问题.从标题中可以看出,我想知道是否可以在 dangerouslySetInnerHTML 属性内使用 React 组件(由 React.createClass 创建).我试过了,但 React 只是打印代码而不进行这样的转换:

I have a question about using React. As you can see from the title, I'm wondering if it is possible to use React component (that is created by React.createClass) inside of dangerouslySetInnerHTML property. I have tried, but React just prints code without transformation like this:

const MySubComponent = React.createClass({
    render() {
        return (<p>MySubComponent</p>);
    }
});

...

let myStringHTML;
myStringHTML += "<ul>";
myStringHTML += "    <li>";
myStringHTML += "        <MySubComponent />";
myStringHTML += "    </li>";
myStringHTML += "</ul>";

const MyComponent = React.createClass({
    render() {
        return (
            <div dangerouslySetInnerHTML={{__html:myStringHTML}}></div>
        );
    }
});

我预料到了

<ul>
    <li>
        <p>MySubComponent</p>
    </li>
</ul>

但是代码和原始字符串一样,这意味着 React 没有转换 MySubComponent.

but the code is just same as original string, and that means React didn't transform MySubComponent.

有没有办法解决这个问题?上面的例子很简单,但我的实际代码非常复杂.非常感谢帮我一把;)

Is there a way to solve this problem? Above example is just simple but my actual code is quite complicated. It will be very thanks gimme a hand ;)

推荐答案

dangerouslySetInnerHTML 需要一个具有 __html 属性的 JS 对象,它应该是有效的 HTML 标记.相反,您在那里提供 <MySubComponent/> 并期望它呈现该组件的 html.React 不会在那里处理 .dangerouslySetInnerHTML 顾名思义应该避免.此外,您在这里尝试完成的工作可以仅通过 React 轻松完成.

dangerouslySetInnerHTML expects a JS object with __html property which should be valid HTML markup. Instead you are providing <MySubComponent /> there and expecting it to render that component's html. React won't process <MySubComponent /> there. dangerouslySetInnerHTML as name suggests should be avoided. Moreover what you are trying to accomplish here can easily be done through React only.

const MySubComponent = React.createClass({
    render() {
        return (<li><p>MySubComponent {this.props.index}</p></li>);
    }
});

const MyComponent = React.createClass({
    render() {
        let subComponentList = [];
        [1,2,3,4,5].forEach(function(i){
            subComponentList.push(<MySubComponent key={i} index={i} />);
        }); 
        return (
            <ul>{subComponentList}</ul>
        );
    }
});

ReactDOM.render(<MyComponent />, mountNode);

这篇关于React:在危险的SetInnerHTML 中使用React 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆