在JSX中的运行时选择React组件的类型 [英] Choosing react component's type at runtime in JSX

查看:105
本文介绍了在JSX中的运行时选择React组件的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个React应用,我想在运行时选择组件的类型.我正在使用ES6和JSX.

I have a react app in which I'd like to choose the type of component at runtime. I'm using ES6 and JSX.

这是我的代码:

import Canvas from '../components/Canvas'
import CanvasTextbox from '../components/CanvasTextbox';


....

export default class CenterPane extends React.Component {

...

render() {
        const canvasKids = [];

        //for (var i = 0; i < 1; i++) {
        //   canvasKids.push(<CanvasTextbox key={i} id={'CanvasTextbox1'} />);
        //};

         for (var i = 0; i < 1; i++) {
             let kid = this.state.kids[i];
             let CanvasComp = kid.type; // evaluates to 'CanvasTextbox '
             canvasKids.push(<CanvasComp key={i} id={kid.id} />);
             console.log(canvasKids)
         };



        return (
            <div>
                Canvas:
                <Canvas
                    name="myCanvas"
                    addChild={this.onAddChild.bind(this)}
                >

                    {canvasKids}


                </Canvas>
           </div>

        );
    }

}

当我按名称引用组件时(如在注释的for循环中),它可以工作.但是,如果我尝试使用变量中的名称,则不会.

When I refer to the component by name, (as in the commented for loop), it works. However, if I try to use the name from a variable, it doesn't.

我尝试按照文档,但仍然没有.

I tried assigning the name to a capitalized variable, as guided in the docs, but still nothing.

我的canvas组件确实有子组件,但它不是React组件,如以下react devtools屏幕截图所示:

My canvas component indeed has the child, but it's not a react component, as seen in this react devtools screengrab:

:

该组件根本不呈现在画布上.

The component is not rendered on the canvas at all.

请帮助.谢谢

推荐答案

无论用什么作为JSX标记",都必须解析为功能(代表HTML标记的小写名称除外).如果kid.type解析为字符串,则它不起作用.

Whatever you use as JSX "tag" has to resolve to a function (lowercase names representing HTML tags are the exception). If kid.type resolves to a string, then it doesn't work.

您必须先构建一个name => component地图:

You'd have to build a name => component map first:

const components = {
  CanvasTextbox,
};

// ...

let CanvasComp = components[kid.type];

这篇关于在JSX中的运行时选择React组件的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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