无法通过 ref 访问子函数? [英] Unable to access child function via ref?

查看:40
本文介绍了无法通过 ref 访问子函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初一切正常,我有一个类似的组件.这个

Initially everything was working fine,I have a component something like. this

  class A extends React.Component {
     constructor(props) {
       super(props);
       this.childRef = null
     }

    componentDidMount() {
     this.childRef = this.refs.b
     // now I can call child function like this
      this.childRef.calledByParent()
    }

    render(){
      <B ref = "b"/>
    }
  }

在其他文件中

     class B extends React.Component {

       calledByParent(){
         console.log("i'm called")
        }

       render(){
        <div> hello </div>
       }
  }
 export default B

到这里它工作正常但是当我在 class B 做这样的事情时 export default connect(mapStateToProps, mapDispatchToProps)(B)

till here it was working fine but when I do something like this in class B export default connect(mapStateToProps, mapDispatchToProps)(B)

它不起作用.我已经从 react-redux 导入了连接

It is not working. I have imported connect from react-redux

推荐答案

connect() 接受 option 作为第四个参数.在此选项参数中,您可以将标志 withRef 设置为 true.在此之后,您可以使用 getWrappedInstance() 来访问 refs 的函数,例如

connect() accepts option as the forth parameter. In this option parameter you can set flag withRef to true. After this you can access functions to refs by using getWrappedInstance() like

class A extends React.Component {
     constructor(props) {
       super(props);
       this.childRef = null
     }

    componentDidMount() {
        this.childRef.getWrappedInstance().calledByParent()
    }

    render(){
      <B ref = {ref => this.childRef = ref}/>
    }
  }

class B extends React.Component {

       calledByParent(){
         console.log("i'm called")
        }

       render(){
        <div> hello </div>
       }
  }
   export default  connect(mapStateToProps, mapDispatchToProps, null, {withRef: true})(B)

这篇关于无法通过 ref 访问子函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆