您现在的位置是:网站首页> 编程资料编程资料
react父组件调用子组件的方式汇总_React_
2023-05-24
318人已围观
简介 react父组件调用子组件的方式汇总_React_
前言
本文是小结类文章,主要总结一下工作中遇到的父组件调用子组件方法。当然除了用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混合使用的时候,不清楚怎么调用子组件方法,这里总结一下,希望对各位小伙伴有所帮助。
到此这篇关于react父组件调用子组件的文章就介绍到这了,更多相关react父组件调用子组件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
相关内容
- 小程序获取用户信息的两种方法详解(getUserProfile和头像昵称填写)_javascript技巧_
- vue渲染大量数据时卡顿卡死解决方法_javascript技巧_
- react电商商品列表的实现流程详解_React_
- TypeScript中类型兼容性的示例详解_javascript技巧_
- Vue引入echarts方法与使用介绍_vue.js_
- 一文详解Vue的响应式原则与双向数据绑定_vue.js_
- UniApp开发H5接入微信登录的全过程_javascript技巧_
- Node.js实现前端后端数据传输加密解密_node.js_
- 微信小程序web-view环境下H5跳转小程序页面方法实例代码_javascript技巧_
- 在微信小程序中使用iconfont的最新图文教程_javascript技巧_
