React JS将类传递为变量

时间:2015-07-22 11:30:39

标签: javascript html reactjs

我想在ReactJS中创建类似下面的东西,但我无法弄清楚我最绝对不想使用DangerouslySetInnerHTML。这只是一个愚蠢的例子,但我希望它能说清楚我想要什么。谢谢你帮助我!

var page = {
    title: <ReactTitle title={this.props.page.name} />
    name: "Me myself and I"
};

var ReactTitle = React.createClass({
    render: function(){
        return (
            <h1>{this.props.title}
        );
    }
})
var NewPage = React.createClass({
    render: function(){
        return (
            <div className="row">
                {this.props.page.title}
                <div className="page-header"><h1>{this.props.page.name}</h1></div>
            </div>
        );
    }
})

React.render(
    <NewPage page={page} />
);

2 个答案:

答案 0 :(得分:2)

您可以像React.createElement一样使用

var page = {
    title: React.createElement(ReactTitle, {title: "My awesome Title"}),
    name: "Me myself and I"
};

Example

但在我看来,最好在ReactTitle内使用NewPage,就像这样

<div className="row">
  <ReactTitle title={this.props.page.title} /> 
  <div className="page-header"><h1>{this.props.page.name}</h1></div>
</div>

Example

答案 1 :(得分:0)

我的解决方案,感谢@Alexander

//Example
var page1 = {
    title: [
        React.createElement("h1", "", "This is my page title");
        React.createElement("div", {className:"page-header"}, "This is the header of page 1");
    ],
    name: "Me myself and I"
};
//So page2, which is slidely different:
//Example
var page2 = {
    title: [
        React.createElement("h2", {className:"h2"}, "Title part",
            React.createElement("span", {className:"silent"}, "Silent part of page title")
        ),
        React.createElement("div", {className:"page-header"}, "This is the header of page 2");
    ],
    name: "Me myself and I"
};