javascript - ReactJs:动态组件加载传递属性

标签 javascript reactjs

我有一个ReactJS组件库,如下代码:

components.js

class Comp1 extends Component {

    render () {
        return (
            <div>Component 1 Text: {this.props.text}</div>
        );
    }
}

class Comp2 extends Component {

    render () {
        return (
            <div>Component 2 Text: {this.props.text}</div>
        );
    }

}

export components = {
    Comp1,
    Comp2
}

主要组件需要根据传递的属性选择要渲染的组件:

ma​​in.js

import { components } from './components';

class Main extends Component {

        getComponent = (name) =>  {
            return components[name];
        };

        render () {

            let comp = this.getComponent(this.props.componentName);

            return (
                <div>
                    <comp   <=== HOW TO CALL THE GIVEN COMPONENT PASSING ITS PROPERTY
                        text={'This is component' + this.props.componentName }
                    />
                </div>
            );
        }
    }


class App extends Component {
        render () {

            return (
                <div>
                    <Main componentName='Comp1' /> // Or 'Comp2'
                </div>
            );
        }
    }
}

我需要在主要代码中呈现组件并传递其属性,但我无法使其工作(请参阅代码注释)。一个简单的 {comp} 呈现组件,但我需要能够相应地传递它的属性。

我尝试过的:

{comp text={'This is component' + this.props.componentName}}
<comp text={'This is component' + this.props.componentName}/>

它们都不起作用。

最佳答案

您的组件名称需要以大写字符开头。所以它应该看起来像

import { components } from './components';

class Main extends Component {

        getComponent = (name) =>  {
            return components[name];
        };

        render () {

            let Comp = this.getComponent(this.props.componentName);

            return (
                <div>
                    <Comp text={'This is component' + this.props.componentName }
                    />
                </div>
            );
        }
    }


class App extends Component {
        render () {

            return (
                <div>
                    <Main componentName='Comp1' /> // Or 'Comp2'
                </div>
            );
        }
    }
}

关于javascript - ReactJs:动态组件加载传递属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45890853/

相关文章:

javascript - 如何在每次鼠标悬停事件时更改单个 div 的颜色?

javascript - Selenium: "is not clickable at point"如何等待所有脚本加载完毕

reactjs - 重定向到/signin后,Electron CRA应用程序返回黑屏

reactjs - React-Toolbox:如何应用主题

node.js - Nodejs - 使用预签名的 url 从 s3 存储桶中下载文件

javascript - 如何在 firebase 更新后返回成功数据

javascript - 当外部链接打开选项卡时,页面滚动到顶部还修复了导航栏

javascript - JavaScript 和 jQuery 中的一些函数符号

reactjs - React 将 onMouseHover 传递给子组件

javascript - 自动完成时的空密码输入值 (React.js)