最初一切正常,我有一个类似的组件。 这个
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/