React父子组件交互之使用onRef
2018-11-01 本文已影响2人
芒果加奶
父子组件之间通信除了通过props
还可以通过ref
进行通信。
// Parent
import React, { Component } from "react";
import FileUpload from ".Fileload";
class Parent extends Component {
handleClick = () = {
this.uploadChild.handleSubmit();
}
onRef = ref => {
this.child = ref;
};
render() {
return (
<div>
<FileUpload onRef={this.onRef} />
<button onClick={this.handleClick} />
</div>
);
}
}
export default Parent;
//Child
import React, { Component } from "react";
class Child extends Component {
componentDidMount() {
this.props.onRef(this);
}
handleSubmit() {
console.log('调用子组件方法')
}
render() {
return (
<div>666</div>
);
}
}
export default (Child);
原理:
当在子组件中调用onRef函数时,正在调用从父组件传递的函数。this.props.onRef(this)这里的参数指向子组件本身,父组件接收该引用作为第一个参数:onRef = {ref =>(this.child = ref)}然后它使用this.child保存引用。之后,可以在父组件内访问整个子组件实例,并且可以调用子组件函数。