纯函数组件 react Hook
//父组件
import React, {useRef} from "react";
import Child from '../Child';
let Parent = () => {
const childRef = useRef();
const updateChildState = () => {
console.log('调用子组件:', childRef)
// changeVal就是子组件暴露给父组件的方法
childRef.current.changeVal('哈哈');
}
return (
<div>
<button onClick={updateChildState}>触发子组件方法</button>
<Child ref={childRef} />
</div>
);
}
export default Parent;
//子组件
import React, {useImperativeHandle, forwardRef} from "react";
let Child = (props, ref) => {
// 此处注意useImperativeHandle方法的的第一个参数是目标元素的ref引用
useImperativeHandle(ref, () => ({
// changeVal 就是暴露给父组件的方法
changeVal: (newVal) => {
alert('调用了子组件的方法=>'+newVal)
}
}));
return (
<div>
我是子组件
</div>
);
}
Child = forwardRef(Child)
export default Child;
类组件 class
//父组件
import React, {Component} from 'react';
export default class Parent extends Component {
render() {
return(
<div>
<Child onRef={this.onRef} />
<button onClick={this.click} >click</button>
</div>
)
}
onRef = (ref) => {
this.child = ref
}
click = (e) => {
this.child.childEvent()
}
}
//子组件
class Child extends Component {
componentDidMount(){
this.props.onRef(this)
}
childEvent = () => alert('我是子组件方法')
render() {
return (<div>我是子组件</div>)
}
}