父子组件都为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.myName()
}
}
//子组件
class Child extends Component {
componentDidMount(){ //必须在这里声明,所以 ref 回调可以引用它
this.props.onRef(this)
}
myName = () => alert('my name is haorooms blogs')
render() {
return (<div>haorooms blog test</div>)
}
}
父子组件都为hooks
一般我们会结合useRef,useImperativeHandle,forwardRef等hooks来使用,官方推荐useImperativeHandle,forwardRef配合使用,经过实践发现forwardRef不用其实也是可以的,只要子组件把暴露给父组件的方法都放到useImperativeHandle里面就可以了。
/* FComp 父组件 */
import {useRef} from 'react';
import ChildComp from './child'
const FComp = () => {
const childRef = useRef();
const updateChildState = () => {
// changeVal就是子组件暴露给父组件的方法
childRef.current.changeVal(99);
}
return (
<>
<ChildComp ref={childRef} />
<button onClick={updateChildState}>触发子组件方法</button>
</>
)
}
import React, { useImperativeHandle, forwardRef } from "react"
let Child = (props, ref) => {
const [val, setVal] = useState();
useImperativeHandle(ref, () => ({ // 暴露给父组件的方法
getInfo,
changeVal: (newVal) => {
setVal(newVal);
},
refreshInfo: () => {
console.log("子组件refreshInfo方法")
}
}))
const getInfo = () => {
console.log("子组件getInfo方法")
}
return (
<div>子组件</div>
)
}
Child = forwardRef(Child)
export default Child
父组件为class,子组件为hooks
// 父组件class
class Parent extends Component{
child= {} //主要加这个
handlePage = (num) => {
// this.child.
console.log(this.child.onChild())
}
onRef = ref => {
this.child = ref
}
render() {
return {
<ListForm onRef={this.onRef} />
}
}
}
// 子组件hooks
import React, { useImperativeHandle } from 'react'
const ListForm = props => {
const [form] = Form.useForm()
//重置方法
const onReset = () => {
form.resetFields()
}
}
useImperativeHandle(props.onRef, () => ({
// onChild 就是暴露给父组件的方法
onChild: () => {
return form.getFieldsValue()
}
}))
..............
父组件为hooks,子组件是class
核心逻辑:
//父组件hooks
let richTextRef = {};
// richTextRef.reseditorState();调用子组件方法
<RichText
getRichText={getRichText}
content={content}
onRef={ref => richTextRef = ref}
/>
//子组件class
componentDidMount = () => {
this.props.onRef && this.props.onRef(this);// 关键部分
}
reseditorState = (content) => {
this.setState({
editorState: content ||'-',
})
}