zoukankan      html  css  js  c++  java
  • 三、Antd react 组件调用ref的用法获取实例

    一、组件通过ref传值

    1、方式一

     2、方式二

    当配合withRouter,获取路由的属性(获取请求的url等参数的时候)报错:

     二、Hook的用法

    问题:

     解决:

    组件间通信除了props外还有onRef方法,不过React官方文档建议不要过度依赖ref。本文使用onRef语境为在表单录入时提取公共组件,在提交时分别获取表单信息。

    下面demo中点击父组件按钮可以获取子组件全部信息,包括状态和方法,可以看下demo中控制台打印。

    父组件代码如下:

    // 父组件
    class Parent extends React.Component {
      testRef=(ref)=>{
        this.child = ref
        console.log(ref) // -> 获取整个Child元素
      }
      handleClick=()=>{
        alert(this.child.state.info) // -> 通过this.child可以拿到child所有状态和方法
      }
      render() {
        return <div>
          <Child onRef={this.testRef} />
          <button onClick={this.handleClick}>父组件按钮</button>
        </div>
      }
    }

    子组件代码如下:

    // 子组件
    class Child extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          info:'快点击子组件按钮哈哈哈'
        }
      }
      componentDidMount(){
        this.props.onRef(this)
        console.log(this) // ->将child传递给this.props.onRef()方法
      }
      handleChildClick=()=>{
        this.setState({info:'通过父组件按钮获取到子组件信息啦啦啦'})
      } 
      render(){
        return <button onClick={this.handleChildClick}>子组件按钮</button>
      }
    }
  • 相关阅读:
    MQ怎么解决消息堆积的问题
    怎么解决Mysql的超大分页
    微信小程序开发入门 —— 认识微信小程序
    C++中strcpy()函数和strcpy_s()函数的使用及注意事项
    UML免费建模工具
    UML 各种图总结精华
    TIFF 文件格式
    LIBTIFF+VS15+WIN10编译
    LIBTIFF VS2013下编译LIBTIFF4.0.9
    Qt 多线程之QtConcurrent::map(处理序列容器)
  • 原文地址:https://www.cnblogs.com/fger/p/12355940.html
Copyright © 2011-2022 走看看