react根据传参的不同动态注册不同的子组件

上一篇文章介绍了关于Vue如何根据传参的不同动态注册不同的子组件,实现过程请查阅Vue.extend动态注册子组件,由Vue的这个功能我就自然联想到了使用react该如何实现同样的功能呢。其实,用react实现同样的功能会更简单,不用那么多的API,不用去查找这些平时可能用的很少的API的用法,这也是为什么很多人喜欢react的原因,react只提供了一些核心的API,至于怎么实现特定的功能,你自己想办法去实现咯,这就是足够灵活啊!!!

需要导入不同的组件还是用到了import和它的then回调方法,代码如下:

import React, { Component } from 'react'

class RegComponent extends Component {
  constructor(props){
    super(props)

    this.state = {
      component: null,
    }

  regComponentHandle(componentName){
    import(`@/pages/${componentName}`).then(res => {
      let { default: component } = res;
      this.setState({
        component,
      });
    })
  }

  render(){
    let C = this.state.component;
    let data = {
      mgs: "动态组件传参"
    }
    const props = {...this.props, data};

    return (
      <div>
        <p><button type="button " onClick={this.regComponentHandle.bind(this, 'customHooks')}>动态注册组件</button></p>

        {C ? <C {...props } /> : null}
      </div>
    )
  }
}

export default RegComponent

打完收工!

是不是很简单?

父组件向子组件传参,也很简单,如{C ? <C {...props } /> : null}

转载于:https://www.cnblogs.com/tnnyang/p/10949017.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值