reactjs:将现有的html包装到组件中

时间:2016-11-17 06:31:06

标签: javascript reactjs typescript

鉴于现有的html。

<component text="one"><h1>First Component</h1></component>
<component text="two"><h1>Second Component</h1></component>
<component text="three"><h2>Third Component</h2></component>

我希望将这些组件包装在一个react类中,该类从现有DOM中获取text属性。此外,现有标记应该在组件内部呈现。

我有一个部分有效的解决方案:

import * as React from "react";
import * as DOM from "react-dom";
import $ from "jquery";

export interface IWellProps {
    text: string
}

export class Well extends React.Component<IWellProps, {}> {
    render() {
        return <div>
            <span>{this.props.text}</span>
            <div>{this.props.children}</div>
        </div>;
    }
}

$("component")
    .each((i, e) => {
        DOM.render(<Well text={$(e).attr("text")}>{$(e).html()}</Well>, e);
        // version below renders html... the above does not.
        // is there not an api to convert text into `react.createElement` calls
        // DOM.render(<Well text={$(e).attr("text")}><h1>test</h1></Well>, e);
    });

我目前的实施部分有效,但使用jquery hack?来创建组件。我预感到当组件开始使用事件和其他反应复杂时会有一些反弹。

  • text属性按原样从原始html呈现。
  • 内部html 呈现为文字而非

enter image description here

0 个答案:

没有答案