我正在研究Meteor + React项目。 请原谅我在这里听到一个小菜鸟,但我需要一些动态调用React组件的帮助。 例如,我有三个组件<ComponentA /> , <ComponentB />和<ComponentC /> 。 但是,我想动态渲染它们;
var comp = /*some function that brings a string here*/; // this variable 'comp' could //be either of the ComponentA, ComponentB and ComponentC.将此comp变量作为反应组件呈现的最佳方法是什么?
以下是系统应如何工作:
if (Meteor.isClient) { WelcomeComponent = React.createClass({ render() { return <div><h1>Hello, {this.props.name}</h1></div> } }); GoodbyeComponent = React.createClass({ render() { return <div><h1>Bye Bye, {this.props.name}</h1></div> } }); MainLayout = React.createClass({ render() { return <div> <header> This is our header </header> <main> {this.props.content} </main> <footer> This is our footer </footer> </div> } }); if (login){ var comp = 'WelcomeComponent'; }else{ var comp = 'GoodbyeComponent'; } // I want above 'comp' variable to be used for rendering/loading/producing respective component ReactLayout.render(MainLayout, {content:<WelcomeComponent name="Kavish"/>}) // ReactLayout.render(MainLayout, {content:<GoodbyeComponent name="Kavish"/>}) }comp变量可以是字符串格式的组件名称。 请告知如何使用变量comp调用函数来加载所需的组件。
I am working on a Meteor + React project. Excuse me for sounding a little noob here, but I need some help with calling a React component dynamically. For instance, I have three components <ComponentA />, <ComponentB /> and <ComponentC />. However, I want to render them dynamically;
var comp = /*some function that brings a string here*/; // this variable 'comp' could //be either of the ComponentA, ComponentB and ComponentC.What is the best way to render this comp variable as a react component?
Following is how the system should work:
if (Meteor.isClient) { WelcomeComponent = React.createClass({ render() { return <div><h1>Hello, {this.props.name}</h1></div> } }); GoodbyeComponent = React.createClass({ render() { return <div><h1>Bye Bye, {this.props.name}</h1></div> } }); MainLayout = React.createClass({ render() { return <div> <header> This is our header </header> <main> {this.props.content} </main> <footer> This is our footer </footer> </div> } }); if (login){ var comp = 'WelcomeComponent'; }else{ var comp = 'GoodbyeComponent'; } // I want above 'comp' variable to be used for rendering/loading/producing respective component ReactLayout.render(MainLayout, {content:<WelcomeComponent name="Kavish"/>}) // ReactLayout.render(MainLayout, {content:<GoodbyeComponent name="Kavish"/>}) }comp variable could either of the components' name in string format. Please advise how to call a function to load required component with using the variable comp.
最满意答案
您可以将className渲染为:
var comp = this.props.type; // should be string var actualComponent = window[comp];现在,如果您正在使用ReactLayout:
ReactLayout.render(actualComponent, {... your props here});You can get the className to render like:
var comp = this.props.type; // should be string var actualComponent = window[comp];Now if you are using ReactLayout use:
ReactLayout.render(actualComponent, {... your props here});更多推荐
发布评论