forwardRef?中React父組件控制子組件的實現(xiàn)代碼
forwardRef 中React父組件控制子組件
作用:forwardRef 用于拿到父組件傳入的 ref 屬性,這樣在父組件便能通過 ref 控制子組件。
父組件:
import { useRef } from "react"; import About from "./comment/About"; //引入子組件 function App() { const typeRef = useRef(); ? const bool = false;//定義一個參數(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}>點擊</button> </> ); } ? export default App;
- 父組件可以通過props向子組件傳遞參數(shù),和方法。
- 父組件通過 typeRef.current,調(diào)用在子組件中的方法和屬性
子組件:
import React, { forwardRef } from "react"; ? /** forwardRef渲染函數(shù)只接受兩個參數(shù):props和ref,必須要傳這兩個參數(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; ?
子組件通過props接收父組件的方法和參數(shù),進(jìn)行調(diào)用
關(guān)于React函數(shù)式組件父組件通過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,()=>({ //這里寫上子組件的方法 getdata() })) }
到此這篇關(guān)于forwardRef - React父組件控制子組件的文章就介紹到這了,更多相關(guān)React父組件控制子組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react?card?slider實現(xiàn)滑動卡片教程示例
這篇文章主要為大家介紹了react?card?slider實現(xiàn)滑動卡片教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09React父組件數(shù)據(jù)實時更新了,子組件沒有更新的問題
這篇文章主要介紹了React父組件數(shù)據(jù)實時更新了,子組件沒有更新的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03React教程之封裝一個Portal可復(fù)用組件的方法
react的核心之一是組件,下面這篇文章主要給大家介紹了關(guān)于React教程之封裝一個Portal可復(fù)用組件的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01