三、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>
  }
}
原文地址:https://www.cnblogs.com/fger/p/12355940.html