呼叫方法:1、類別元件中的呼叫可以利用React.createRef()、ref的函數式宣告或props自訂onRef屬性來實作;2、函式元件、Hook元件中的呼叫可以利用useImperativeHandle或forwardRef拋出子元件ref來實作。
本教學操作環境:Windows7系統、react18版、Dell G3電腦。
在React中,我們常在子元件中呼叫父元件的方法,一般用props回呼即可。但是有時候也需要在父元件中呼叫子元件的方法,透過這種方法實現高內聚。有多種方法,請按需服用。
類別元件中
1、React.createRef()
優點:簡單易懂,用ref指向。
-
缺點:使用了HOC的子元件不可用,無法指向真是子元件
例如一些常用的寫法,mobx的@observer包裹的子元件就不適用此方法。
import React, { Component } from 'react'; class Sub extends Component { callback() { console.log('执行回调'); } render() { return <div>子组件</div>; } } class Super extends Component { constructor(props) { super(props); this.sub = React.createRef(); } handleOnClick() { this.sub.callback(); } render() { return ( <div> <Sub ref={this.sub}></Sub> </div> ); } }
2、ref的函數式宣告
- 優點:ref寫法簡潔
- 缺點:使用了HOC的子元件不可用,無法指向真是子元件(同上)
使用方法和上述的一樣,就是定義ref的方式不同。
... <Sub ref={ref => this.sub = ref}></Sub> ...
3、使用props自訂onRef屬性
- #優點:假如子元件是嵌套了HOC,也可以指向真實子元件。
- 缺點:需要自訂props屬性
import React, { Component } from 'react'; import { observer } from 'mobx-react' @observer class Sub extends Component { componentDidMount(){ // 将子组件指向父组件的变量 this.props.onRef && this.props.onRef(this); } callback(){ console.log("执行我") } render(){ return (<div>子组件</div>); } } class Super extends Component { handleOnClick(){ // 可以调用子组件方法 this.Sub.callback(); } render(){ return ( <div> <div onClick={this.handleOnClick}>click</div> <Sub onRef={ node => this.Sub = node }></Sub> </div>) } }
函數元件、Hook元件
1、useImperativeHandle
- 優點: 1.寫法簡單易懂 2.假如子元件嵌套了HOC,也可以指向真實子元件
- 缺點: 1、需要自訂props屬性 2.需要自訂暴露的方法
import React, { useImperativeHandle } from 'react'; import { observer } from 'mobx-react' const Parent = () => { let ChildRef = React.createRef(); function handleOnClick() { ChildRef.current.func(); } return ( <div> <button onClick={handleOnClick}>click</button> <Child onRef={ChildRef} /> </div> ); }; const Child = observer(props => { //用useImperativeHandle暴露一些外部ref能访问的属性 useImperativeHandle(props.onRef, () => { // 需要将暴露的接口返回出去 return { func: func, }; }); function func() { console.log('执行我'); } return <div>子组件</div>; }); export default Parent;
2、forwardRef
使用forwardRef拋出子元件的ref
這個方法其實更適合自訂HOC。但問題是,withRouter、connect、Form.create等方法並不能拋出ref,假如Child本身就需要嵌套這些方法,那基本上就不能混著用了。 forwardRef本身也是用來拋出子元素,如input等原生元素的ref的,並不適合做組件ref拋出,因為組件的使用場景太複雜了。
import React, { useRef, useImperativeHandle } from 'react'; import ReactDOM from 'react-dom'; import { observer } from 'mobx-react' const FancyInput = React.forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return <input ref={inputRef} type="text" /> }); const Sub = observer(FancyInput) const App = props => { const fancyInputRef = useRef(); return ( <div> <FancyInput ref={fancyInputRef} /> <button onClick={() => fancyInputRef.current.focus()} >父组件调用子组件的 focus</button> </div> ) } export default App;
總結
父元件調子元件函數有兩種情況
- 子元件無HOC巢狀:建議使用ref直接呼叫
- 有HOC嵌套:推薦使用自訂props的方式
以上是React父元件怎麼呼叫子元件的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互動,可及可訪問。 1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒體綜合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityActibility.2)and tagsallowsemlessallowseamelesseamlessallowseamelesseamlesseamelesseamemelessmultimedimeDiaiaembediiaembedplugins.3)。 3)3)

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrenerabilnerabilityLikeClickLickLickLickjAckJackJacking.2)

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

使用ID選擇器在CSS中並非固有地不好,但應謹慎使用。 1)ID選擇器適用於唯一元素或JavaScript鉤子。 2)對於一般樣式,應使用類選擇器,因為它們更靈活和可維護。通過平衡ID和類的使用,可以實現更robust和efficient的CSS架構。

html5'sgoalsin2024focusonrefinement和optimization,notNewFeatures.1)增強performanceandeffipedroptimizedRendering.2)inviveAccessibilitywithRefinedwithRefinedTributesAndEllements.3)explityconcerns,尤其是withercercern.4.4)

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供應,2)語義結構,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,簡化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Dreamweaver Mac版
視覺化網頁開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能