从字符串创建React类的实例 [英] Create an instance of a React class from a string

查看:60
本文介绍了从字符串创建React类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,其中包含类的名称(这来自json文件)。这个字符串告诉我的模板类用于数据的布局/模板(也在json中)。问题是我的布局未显示。

I have a string which contains a name of the Class (this is coming from a json file). This string tells my Template Class which layout / template to use for the data (also in json). The issue is my layout is not displaying.

Home.jsx:

//a template or layout.
var Home = React.createClass({
  render () {
    return (
    <div>Home layout</div>
    )
  }
});

Template.jsx:

Template.jsx:

var Template = React.createClass({
  render: function() {
    var Tag = this.props.template; //this is the name of the class eg. 'Home'
    return (
        <Tag />
    );
  }
});

我没有任何错误,但也没有看到布局/家庭教室。我已经检查了props.template,并记录了正确的信息。另外,我可以在DOM中看到home元素。但是它看起来像这样:

I don't get any errors but I also don't see the layout / Home Class. I've checked the props.template and this logs the correct info. Also, I can see the home element in the DOM. However it looks like this:

<div id='template-holder>
    <home></home>
</div>

如果我将以下行更改为:

If I change following line to:

var Tag = Home;
//this works but it's not dynamic!

任何想法,我该如何解决?我敢肯定,这只是简单的解决方法,还是我正在做一些愚蠢的事情。帮助将不胜感激。抱歉,这已经被问到了(我找不到)。

Any ideas, how I can fix this? I'm sure it's either simple fix or I'm doing something stupid. Help would be appreciated. Apologies if this has already been asked (I couldn't find it).

谢谢,
Ewan

Thanks, Ewan

推荐答案

这将不起作用:

var Home = React.createClass({ ... });

var Component = "Home";
React.render(<Component />, ...);

但是,这将是:

var Home = React.createClass({ ... });

var Component = Home;
React.render(<Component />, ...);

所以您只需要找到一种在 string 首页 组件类 Home 。一个简单的对象将用作基本注册表,如果需要更多功能,则可以从那里进行构建。

So you simply need to find a way to map between the string "Home" and the component class Home. A simple object will work as a basic registry, and you can build from there if you need more features.

var components = {
  "Home": Home,
  "Other": OtherComponent
};

var Component = components[this.props.template];

这篇关于从字符串创建React类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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