无法从字符串创建react元素

认真思考

我有一个工厂,我想在其中生成反应组件。现在我有LoadMigrate直接传递导入的名称可以正常工作:

...

return React.createElement(Migrate, {
    node: node,
    diagramEngine: diagramEngine
});

但我想动态插入名称。

...    

var ElementToCreate = node.state.manipulator.name;

return React.createElement(ElementToCreate, {
    node: node,
    diagramEngine: diagramEngine
});

但这会因错误消息而爆炸:

警告:未知的道具nodediagramEngine在标签。从元素中移除这些道具

传递原始字符串“迁移”或“加载”也将失败。遵循此处的提示无法帮助我确定问题。有任何想法吗?

AKX

如果您将字符串作为第一个参数传递给React.createElement,则它将被视为HTML标记名称,这不是您想要的名称。

而是使用注册表从名称映射到实际的组件类:

import Foo from './Foo';
import Bar from './Bar';
import Quux from './Quux';

const TYPE_REGISTRY = {
    // Using ES object literal shorthand to
    // avoid repeating the names
    Bar,
    Foo,
    Quux,
};

// ...

class ... {

    render() {
        // typeName would be one of "Bar", "Foo" or "Quux".
        const typeName = node.state.manipulator.name;
        const element = TYPE_REGISTRY[typeName];
        if(!element) {
            return <div>Invalid type name {typeName}</div>;
        }
        return React.createElement(element, {node, diagramEngine});
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章