dynamic呈现React组件

在React JSX中,似乎不可能做这样的事情:

render: function() { return ( <{this.props.component.slug} className='text'> {this.props.component.value} </{this.props.component.slug}> ); } 

我得到一个parsing错误:意外的标记{。 这不是React可以处理的吗?

我正在devise这个组件,以便在这个引擎下,存储在this.props.component.slug中的值将包含有效的HTML元素(h1,p等)。 有什么办法可以做这个工作吗?

你不应该把组件塞进花括号中:

 var Hello = React.createClass({ render: function() { return <this.props.component.slug className='text'> {this.props.component.value} </this.props.component.slug>; } }); React.renderComponent(<Hello component={{slug:React.DOM.div, value:'This is my header'}} />, document.body); 

这是一个工作小提琴: http : //jsfiddle.net/kb3gN/6668/

此外,你可以findJSX编译器有助于debugging这些types的错误: http : //facebook.github.io/react/jsx-compiler.html

正如nilgun先前所指出的那样,组件slu should不应该用大括号包裹起来。

如果您决定将其存储在variables中,请确保它以大写字母开头。

这里是一个例子:

 var Home = React.createClass({ render: function() { return ( <div> <h3>This is an input</h3> <CustomComponent inputType="input" /> <h3>This is a text area</h3> <CustomComponent inputType="textarea" /> </div> ); } }); var CustomComponent = React.createClass({ render: function() { // make sure this var starts with a capital letter var InputType = this.props.inputType; return <InputType />; } }); React.render(<Home />, document.getElementById('container')); 

这是一个工作小提琴: https : //jsfiddle.net/janklimo/azzohvn1/4/

编辑 :也许你忘了添加/** @jsx React.DOM */在js的开头?

你可以使用React.DOM

 render: function() { return React.DOM[this.props.component.slug](null, this.props.component.value); } 

http://jsbin.com/rerehutena/2/edit?html,js,output

我不是一个React专家,但我认为每个组件都应该在开始时使用特定的标签进行构build。 所以它可以提出一个明确的目的本身。

如果你的意图是注入实际的组件,你可以做这样的事情,这对于testing非常方便,或者你想要dynamic注入组件来渲染。

 var MyComponentF=function(ChildComponent){ var MyComponent = React.createClass({ getInitialState: function () { return { }; }, componentDidMount: function () { }, render: function () { return ( <div className="MyComponent"> <ChildComponent></ChildComponent> </div> ); } }); return MyComponent; }; var OtherComponentF=function(){ var OtherComponent = React.createClass({ getInitialState: function () { return { }; }, componentDidMount: function () { }, render: function () { return ( <div className="OtherComponent"> OtherComponent </div> ); } }); return OtherComponent; }; var AnotherComponentF=function(){ var AnotherComponent = React.createClass({ getInitialState: function () { return { }; }, componentDidMount: function () { }, render: function () { return ( <div className="AnotherComponent"> AnotherComponent </div> ); } }); return AnotherComponent; }; $(document).ready(function () { var appComponent = MyComponentF(OtherComponentF()); // OR var appComponent = MyComponentF(AnotherComponentF()); // Results will differ depending on injected component. ReactDOM.render(React.createElement(appComponent), document.getElementById("app-container")); });