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

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

须要导入不一样的组件仍是用到了import和它的then回调方法,代码以下:react

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

打完收工!this

是否是很简单?code

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

相关文章
相关标签/搜索