Reactjs 动态组件进行反应

Reactjs 动态组件进行反应,reactjs,Reactjs,我对React中的动态组件有问题。这是我的密码: Comp1.jsx: import React from 'react'; export default class Comp1 extends React.Component { // .... } Parent.jsx: import React from 'react'; import Comp1 from './components/Comp1.jsx'; const ConfigComponents = { comp

我对React中的动态组件有问题。这是我的密码:

Comp1.jsx:

import React from 'react';
export default class Comp1 extends React.Component {
    // ....
}
Parent.jsx:

import React from 'react';
import Comp1 from './components/Comp1.jsx';

const ConfigComponents = {
    comp1: Comp1
};

export const ConfigComponent = (props) => {
    let Component = ConfigComponents[ props.type ];

    return (
        <Component { ...props} />
    );
}

export default class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            componentToAdd: 'comp1'
        }
    }

    render() {
         return (
           <div>
             <ConfigComponent type={this.state.componentToAdd} />
           </div>
         )
    }
}
在sof和Internet上,我似乎使用了适当的语法(导入时没有{}),所以我不明白我缺少了什么。我跟随这篇帖子:

2件事

  • 您的
    父级
    的呈现方法没有
    返回
    语句
  • 您将
    组件添加到
    而不是
    状态添加到
    配置组件
  • 将父组件的
    修复为

    导出默认类父类扩展React.Component{
    建造师(道具){
    超级(道具);
    此.state={
    状态添加:“comp1”
    };
    }
    render(){
    返回(
    );
    }
    }
    

    您的
    家长的
    呈现
    方法缺少
    返回
    语句。在
    处键入这些都是我写问题时键入的。在我的代码里没关系,我相信问题在于你怎么称呼Comp1。编写时:return();我建议您修改不同的语法,或者直接使用React.CreateElement来找出错误所在。
    React
    版本是什么?这些都是打字错误,我没有提供真实的代码和名称。我已经编辑了我的问题。错误不是由此引起的…可能是
    Comp1
    组件有问题?带有您描述的错误的codesandbox可能会有所帮助。以下代码有效:{COMPONENT_CONFIG[this.state.componentToAdd]}with export const COMPONENT_CONFIG={comp1:()}
    React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.