React父組件調用子組件中的方法實例詳解
文章中涉及 ref 的應用僅為父組件調用子組件場景下的應用方式,并未涵蓋 ref 的所有應用方式!
Class組件
1. 自定義事件
Parent.js
import React, { Component } from 'react'; import Child from './Child'; class Parent extends Component { componentDidMount () { console.log(this.childRef) } handleChildEvent = (ref) => { // 將子組件的實例存到 this.childRef 中, 這樣整個父組件就能拿到 this.childRef = ref } //按鈕事件處理 handleClick = () => { // 通過子組件的實例調用組組件中的方法 this.childRef.sendMessage() } render () { return ( <> <Child onChildEvent={this.handleChildEvent} /> <button onClick={this.handleClick}>Trigger Child Event</button> </> ); } } export default Parent;
Child.js
import React, { Component } from 'react'; class Child extends Component { //子組件完成掛載時, 將子組件的方法 this 作為參數傳到父組件的函數中 componentDidMount () { // 在子組件中調用父組件的方法,并把當前的實例傳進去 this.props.onChildEvent(this) } // 子組件的方法, 在父組件中觸發(fā) sendMessage = () => { console.log('sending message') } render () { return ( <div>Child</div> ); } } export default Child;
2. 使用 React.createRef()
ParentCmp.js
import React, { Component } from 'react'; import ChildCmp from './ChildCmp'; export default class ParentCmp extends Component { constructor(props) { super(props) // 創(chuàng)建Ref this.childRef = React.createRef() } // 按鈕事件 handleClick = () => { // 直接通過 this.childRef.current 拿到子組件實例 this.childRef.current.sendMessage() } render () { return ( <> <ChildCmp ref={this.childRef} /> <button onClick={this.handleClick}>Trigger Child Event</button> </> ); } }
而子組件就是一個普通的組件
ChildCmp.js
import React, { Component } from 'react'; export default class ChildCmp extends Component { sendMessage = () => { console.log('sending message') } render () { return 'Child'; } }
3. 使用回調Refs
回調 Refs 是另一種設置 Ref 的方式,它能助你更精細地控制何時 refs 被設置和解除。
不同于傳遞 createRef() 創(chuàng)建的 ref 屬性,需要傳遞一個函數。
訪問 Ref 的時候也不需要 current。
ParentCmp.js
import React, { Component } from 'react'; import ChildCmp from './ChildCmp'; export default class ParentCmp extends Component { constructor(props) { super(props) // 創(chuàng)建 Ref,不通過 React.createRef() this.childRef = null } // 設置 Ref setChildRef = (ref) => { this.childRef = ref } // 按鈕事件 handleClick = () => { // 直接通過 this.childRef 拿到子組件實例 this.childRef.sendMessage(`Trigger Child Event from Parent`) } render () { return ( <> <ChildCmp ref={this.setChildRef} /> <button onClick={this.handleClick}>Trigger Child Event</button> </> ); } }
而子組件還是一個普通的組件
ChildCmp.js
import { Component } from 'react'; export default class ChildCmp extends Component { sendMessage = (message) => { console.log('sending message:', message) } render () { return 'Child'; } }
【注】對比自定義事件方式,回調 Refs 更像是精簡的自定義事件方式:
- 自定義事件名稱變成了 ref
- 子組件內不需要手動綁定
Function組件
默認情況下,不能在函數組件上使用 ref 屬性,因為它們沒有實例。所以上面的兩種方式是行不通的。
解決辦法就是使用 forwardRef 和 useImperativeHandle。
不過在函數的內部是可以使用 useRef 鉤子來獲取組件內的 DOM 元素。
Parent.js
import React, { useRef } from 'react'; import Child from './Child'; const Parent = () => { // 通過 Hooks 創(chuàng)建 Ref const childRef = useRef(null) const handleClick = () => { childRef.current.sendMessage() } return ( <> <Child ref={childRef} /> <button onClick={handleClick}>Trigger Child Event</button> </> ); } export default Parent;
Child.js
import React, { forwardRef, useImperativeHandle } from 'react'; const Child = forwardRef((props, ref) => { //將子組件的方法 暴露給父組件 useImperativeHandle(ref, () => ({ sendMessage })) const sendMessage = () => { console.log('sending message') } return ( <div>Child</div> ); }) export default Child;
注:
上面的例子中只是簡單地演示了父子組件之間的方法調用,當然實際情況中子組件中可以也會有自己的 ref 指向自己內部的 DOM 元素,不過這些原理都是一樣的。
補充:子組件調用父組件方法
子組件中調用父組件的setId方法
父組件
<NavBarX item={item} current={current} getBatchDetails={(id) => this.getBatchDetails(0, id)} setId={(id, callback) => this.setState({ id }, callback)} onRef={this.onNavBarXRef} />
子組件
this.props.setId(prePageId, () => { getBatchDetails(prePageId) })
總結
到此這篇關于React父組件調用子組件中方法的文章就介紹到這了,更多相關React父組件調用子組件方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
React Native模塊之Permissions權限申請的實例相機
這篇文章主要介紹了React Native模塊之Permissions權限申請的實例相機的相關資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-09-09react開發(fā)中如何使用require.ensure加載es6風格的組件
本篇文章主要介紹了react開發(fā)中如何使用require.ensure加載es6風格的組件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05JavaScript中的useRef 和 useState介紹
這篇文章主要給大家分享的是 JavaScript中的useRef 和 useState介紹,下列文章,我們將學習 useRef 和 useState hook是什么,它們的區(qū)別以及何時使用哪個。 這篇文章中的代碼示例將僅涉及功能組件,但是大多數差異和用途涵蓋了類和功能組件,需要的朋友可以參考一下2021-11-11React.js入門實例教程之創(chuàng)建hello world 的5種方式
React 是近期非常熱門的一個前端開發(fā)框架。應用非常廣泛,接下來通過本文給大家介紹React.js入門實例教程之創(chuàng)建hello world 的5種方式 ,需要的朋友參考下吧2016-05-05