• 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
    

    以上是react有状态组件的实现方法,那么无状态组件也就是函数式组件的实现方法呢?
    函数式组件的实现方法要借助react hooks的useState方法来实现:

    const RegComponent = () => {
      const [component, setComonent] = useState({ Com: null })
    
      const regComponentHandle = (componentName) => {
        import(`@/pages/${componentName}`).then(res => {
          let { default: component } = res;
    
          setComonent({ Com: component });
          
        })
      }
    
      const { Com } = component
    
      return (
        <div>
          <p><Button type="primary" onClick={() => regComponentHandle('useContext')}>动态注册组件</Button></p>
          {Com ? <Com {...props} /> : null}
        </div>
      );
    }
    
    export default RegComponent
    

    注意,这里需要特别说明一下:
    1、useState方法可以接收一个函数作为参数,但是该函数中的代码只会在初始化时执行一次;
    2,、由于useState方法可以接收一个函数作为参数,于是我就想当然的认为可以把一个函数组件作为参数传给useState,也想当然的认为const [component, setComonent] = useState()中的component是可以拿到传过来的函数组件的,结果很出人意料,component可以获取到传过来的参数,但此时的component的值已经不是一个函数组件了,而是一个$$typeof: Symbol(react.element), type: ƒ, key: null, ref: null,当然了,打印出来的component的值不止这些,还有一长串,这里我就不全部贴出来了。很显然,这不是一个组件,好像是一个独一无二(Symbol)的react.element,也就不能显示到页面中了,所以我就绕了一个弯,把拿到的函数组件赋值给一个对象的属性,然后再通过该属性获取到这个函数组件就完美解决了这个问题。
    3、说一下为什么用到了react hooks的useState方法,因为函数式组件没有生命周期,没有setState,所以要想在函数式组件中更新数据并实时显示更新后的数据,我能想到的就只有react hooks的useState方法以及dva模式(dva模式就那几个API,用起来很简单,没什么说的)了。

  • 相关阅读:
    【转载】设计模式_单例模式(学习)
    【转载】设计模式_抽象工厂模式(学习)
    【转载】设计模式_工厂方法(学习)
    【转载】设计模式_六大原则(学习)
    【转载】设计模式_简单工厂模式(学习)
    java有用的启动参数
    linux freetds操作mssql
    ansible 控制windows
    nginx 版本介绍
    tar 压缩去除目录
  • 原文地址:https://www.cnblogs.com/tnnyang/p/10949017.html
Copyright © 2020-2023  润新知