共计 2107 个字符,预计需要花费 6 分钟才能阅读完成。
前言
本文是小结类文章,主要总结一下工作中遇到的父组件调用子组件方法。当然除了用 ref 之外还有很多其他方式,本文仅仅列举 ref 的方式。分别介绍父子组件都为 class;父子组件都是 hooks;父组件是 class 子组件是 hooks;父组件是 hooks,子组件是 class 的各种情况的调用方式。
父子组件都为 class
父子组件都是 class,父组件调用子组件方式比较传统,方法如下:
// 父组件
import React, {Component} from 'react';
export default class Parent extends Component {render() {
return(
)
}
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 (haorooms blog test)
}
}
父子组件都为 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 (
>
)
}
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 ( 子组件
)
}
Child = forwardRef(Child)
export default Child
父组件为 class, 子组件为 hooks
其实就是上面的结合体。子组件还是用 useImperativeHandle,可以结合 forwardRef,也可以不用。
// 父组件 class
class Parent extends Component{child= {} // 主要加这个
handlePage = (num) => {
// this.child.
console.log(this.child.onChild())
}
onRef = ref => {this.child = ref}
render() {
return {
}
}
}
// 子组件 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
这里其实和上面差不多,react 主要 dom 省略,仅展示精华部分
// 父组件 hooks
let richTextRef = {};
// richTextRef.reseditorState(); 调用子组件方法
richTextRef = ref}
/>
// 子组件 class
componentDidMount = () => {this.props.onRef && this.props.onRef(this);// 关键部分
}
reseditorState = (content) => {
this.setState({editorState: content ||'-',})
}
小结
本文主要是总结,有些朋友在 hooks 或者 class 混合使用的时候,不清楚怎么调用子组件方法,这里总结一下,希望对各位小伙伴有所帮助。
正文完