简体   繁体   English

如何在reactjs中动态加载组件?

[英]How to load Component dynamically in reactjs?

I'm working on a Reactjs + React-motion project, in a "modal window" (let's say) I'd like to mount or load a component dynamically, if that's possible ? 我正在一个“模式窗口”(比如说)中进行一个Reactjs + React-motion项目,如果可能的话,我想动态地安装或加载一个组件?

My solution so far: I couldn't find a way, so it seems that it's easier to have the component in place, and hide it, then toggle a class or style on state change, revealing the hidden component and only after the "modal window" transition finishes. 到目前为止,我的解决方案是:我找不到方法,因此似乎很容易将组件放置到位,将其隐藏,然后在状态更改时切换类或样式,从而显示隐藏的组件,并且仅在“模式”之后窗口”转换完成。

Sharing some code below where it's easier to understand what I'm trying to do. 在下面共享一些代码,可以更轻松地了解我的工作意图。 There's no event handlers and most code was removed, but the onRest (the event callback when the animation finishes is exposed) and also the render fn. 没有事件处理程序,大多数代码已删除,但是onRest (动画结束时的事件回调已公开)以及渲染fn。

class HomeBlock extends React.Component {

    constructor (props) {
        ...

    }

    ...

    motionStyleFromTo () {

        return {
            ...
        };

    }

    onRest () {

        // this is triggered when the Motion finishes the transition

    }

    render () {

        return (
            <Motion onRest={this.onRestCallback.bind(this)} style={this.motionStyleFromTo()}>
                {style =>
                    <div className="content" style={{
                        width: `${style.width}px`,
                        height: `${style.height}px`,
                        top: `${style.top}px`,
                        left: `${style.left}px`
                        }}>
                        [LOAD COMPONENT HERE]
                    </div>
                }
            </Motion>
        );

    }

}

export default HomeBlock;

You can achieve this quite easily. 您可以轻松实现这一目标。 In this example I am rendering a component dynamically based on a prop: 在此示例中,我将基于prop动态渲染组件:

class MyComponent extends React.Component {
  propTypes: {
    display: React.PropTypes.bool
  },
  render() {
    return (
       <div>
         {this.props.display ? <ChildComponent /> : null}
       </div>
    )
  }
}

In your case you may want to use internal component state to mount or unmount the component. 在您的情况下,您可能希望使用内部组件状态来安装或卸载组件。

FYI there are cases where you might prefer or need to use style to hide components instead of destroying them. 仅供参考,在某些情况下,您可能更喜欢或需要使用样式来隐藏组件而不是破坏它们。 There is more about this in the React documenation. React文档中有更多有关此的内容。 See the 'Stateful Children' section here: https://facebook.github.io/react/docs/multiple-components.html 请参阅此处的“有状态的孩子”部分: https : //facebook.github.io/react/docs/multiple-components.html

You can do it using dependency injection and dependency container concept. 您可以使用依赖项注入和依赖项容器概念来实现。 I have provided some sample code at this gist page 我在此要点页面上提供了一些示例代码

https://gist.github.com/SamanShafigh/a0fbc2483e75dc4d6f82ca534a6174d4 https://gist.github.com/SamanShafigh/a0fbc2483e75dc4d6f82ca534a6174d4

So let assume you have 4 components called D1, D2, D3. 因此,假设您有4个组件,分别称为D1,D2,D3。 What you need is to create a dependency injection and a dependency container mechanism. 您需要创建一个依赖项注入和一个依赖项容器机制。 This is a very simple implementation 这是一个非常简单的实现

Imagine you have a config file like this that defines your components 假设您有一个这样的配置文件,它定义了您的组件

export default [
  {
    name:'D1',
    path:'D1'
  },
  {
    name:'D2',
    path:'D2'
  },
  {
    name:'D3',
    path:'D3'
}];

Then you can have a component container something like this 然后,您可以拥有一个类似这样的组件容器

import componentsConfig from 'ComponentsConfig';

let components = {};

for (var i = 0; i < componentsConfig.length; i++) {
  let componentConfig = componentsConfig[i];
  // Check if component is not already loaded then load it
  if (components[componentConfig.name] === undefined) {
    components[componentConfig.name] = require(`${componentConfig.path}`).default;
  }
}

export default components;

Finally in the place you want to load your components you can use your component container to load your components dynamically or in other word you can inject your components 最后,在要加载组件的位置,可以使用组件容器动态加载组件,或者换句话说,可以注入组件

import React, { Component } from 'react';
import ComponentContainer from './ComponentContainer';

class App extends Component {
  render() {
    let components = ['D1', 'D2', 'D3'];

    return (
      <div>
        <h2>Dynamic Components Loading</h2>
        {components.map((componentId) => {
          let Component = ComponentContainer[componentId];
          return <Component>{componentId}</Component>;
        })}
      </div>
    );
  }
}

export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM