reactjs - 无法通过 ref 访问子函数?

标签 reactjs redux react-redux

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

  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

到目前为止,它工作正常,但是当我在 B 类 中执行类似操作时 export default connect(mapStateToProps, mapDispatchToProps)(B)

它不工作。我已经从react-redux导入了connect

最佳答案

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

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)

关于reactjs - 无法通过 ref 访问子函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42025434/

相关文章:

reactjs - 调度操作后 react Redux setState

javascript - Axios ReactJs Laravel : How to retrieve the multiple request Api

jquery - ReactJS - 在表格行上使用 slideDown(切换)?

reactjs - 将数组项替换为另一项而不改变状态

github - 尝试将 webpack 推送到 gh-pages

reactjs - 为什么我的 try catch block 不处理调度错误?

reactjs - Redux、 react 、 typescript : Connect returns view class which requires props

css - (React-redux frontend developer) 我应该使用 css 还是添加另一个框架?

javascript - es6 传播运算符如何处理对象到 Prop 的转换?

javascript - 如何在reactjs中以卡片的形式显示循环数据