forwardRef?中React父組件控制子組件的實(shí)現(xiàn)代碼
forwardRef 中React父組件控制子組件
作用:forwardRef 用于拿到父組件傳入的 ref 屬性,這樣在父組件便能通過(guò) ref 控制子組件。
父組件:
import { useRef } from "react"; import About from "./comment/About"; //引入子組件 function App() { const typeRef = useRef(); ? const bool = false;//定義一個(gè)參數(shù) const toggle = () => { console.log(typeRef) //調(diào)用 typeRef.current里面的數(shù)據(jù) typeRef.current.show(); typeRef.current.close(); console.log(typeRef.current.a); }; // 回調(diào)函數(shù) const select = (item) => { console.log( item, "typeRef"); }; return ( <> <About ref={typeRef} onSelect={select} parameter={bool}></About> <button onClick={toggle}>點(diǎn)擊</button> </> ); } ? export default App;
- 父組件可以通過(guò)props向子組件傳遞參數(shù),和方法。
- 父組件通過(guò) typeRef.current,調(diào)用在子組件中的方法和屬性
子組件:
import React, { forwardRef } from "react"; ? /** forwardRef渲染函數(shù)只接受兩個(gè)參數(shù):props和ref,必須要傳這兩個(gè)參數(shù) */ const About = forwardRef((props, ref) => { //向ref.current添加屬性,在父組件中調(diào)用 ref.current = { show: () => { console.log("show"); }, close: () => { console.log("close"); }, a:false, }; const choseType = () => { console.log(props); //調(diào)用props里的方法和參數(shù) props.onSelect(1); console.log(props.parameter); }; return <div onClick={choseType}>About</div>; }); ? export default About; ?
子組件通過(guò)props接收父組件的方法和參數(shù),進(jìn)行調(diào)用
關(guān)于React函數(shù)式組件父組件通過(guò)ref調(diào)用子組件的方法
使用useImperativeHandle+forwardRef,后者可以不使用
父子組件代碼:
import {useRef} from 'react' import Child from "./child" //父組件 const Parent=()=>{ const cRef=useRef() return( const getChild=()=>{ cRef.current.getdata()//調(diào)用子組件的getdata方法 } <Chile cRef={cRef} />//子組件 <BUtton onClick={getChild}/> ) } export default Parent //子組件 import {useImperativeHandle} from 'React' type Cprops={ cRef } const Child=({cRef})=>{ useImperativeHandle(cRef,()=>({ //這里寫(xiě)上子組件的方法 getdata() })) }
到此這篇關(guān)于forwardRef - React父組件控制子組件的文章就介紹到這了,更多相關(guān)React父組件控制子組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react?card?slider實(shí)現(xiàn)滑動(dòng)卡片教程示例
這篇文章主要為大家介紹了react?card?slider實(shí)現(xiàn)滑動(dòng)卡片教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09React父組件數(shù)據(jù)實(shí)時(shí)更新了,子組件沒(méi)有更新的問(wèn)題
這篇文章主要介紹了React父組件數(shù)據(jù)實(shí)時(shí)更新了,子組件沒(méi)有更新的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03React教程之封裝一個(gè)Portal可復(fù)用組件的方法
react的核心之一是組件,下面這篇文章主要給大家介紹了關(guān)于React教程之封裝一個(gè)Portal可復(fù)用組件的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01React實(shí)現(xiàn)路由鑒權(quán)的實(shí)例詳解
React應(yīng)用中的路由鑒權(quán)是確保用戶僅能訪問(wèn)其授權(quán)頁(yè)面的方式,用于已登錄或具有訪問(wèn)特定頁(yè)面所需的權(quán)限,這篇文章就來(lái)記錄下React實(shí)現(xiàn)路由鑒權(quán)的流程,需要的朋友可以參考下2024-07-07