如何在reactjs中动态加载Component? [英] How to load Component dynamically in reactjs?

查看:432
本文介绍了如何在reactjs中动态加载Component?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Reactjs + React-motion项目,在模态窗口中(比方说)我想动态安装或加载组件,如果可能的话?

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 ?

到目前为止我的解决方案:我找不到方法,所以看起来更容易将组件放在适当位置并隐藏它,然后在状态更改时切换类或样式,揭示隐藏组件,只有在模态窗口转换完成后才会完成。

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.

在下面分享一些代码,以便更容易理解我正在尝试做什么。没有事件处理程序,大多数代码都被删除了,但是 onRest (动画完成后的事件回调曝光)以及渲染fn。

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.

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;


推荐答案

您可以轻松实现这一目标。在这个例子中,我基于一个prop动态渲染一个组件:

You can achieve this quite easily. In this example I am rendering a component dynamically based on a 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.

仅供参考您可能更喜欢或需要使用样式来隐藏组件而不是销毁它们的情况。在React文档中有更多关于此的内容。请参阅此处的有状态儿童部分: https://facebook.github.io/ react / docs / multiple-components.html

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. See the 'Stateful Children' section here: https://facebook.github.io/react/docs/multiple-components.html

这篇关于如何在reactjs中动态加载Component?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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