上一篇文章介紹了關於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