React Hook 父子組件相互調(diào)用函數(shù)方式
React Hook 父子組件相互調(diào)用函數(shù)
1.子組件調(diào)用父組件函數(shù)方法
//父組件
let Father=()=>{
?? ?let getInfo=()=>{
?? ??? ?
?? ?}
?? ?return ()=>{
?? ??? ?<div>
?? ??? ??? ?<Children?
?? ??? ??? ??? ?getInfo={getInfo}
?? ??? ??? ?/>
?? ??? ?</div>
?? ?}
}//子組件
let Children=(param)=>{
?? ?return ()=>{
?? ??? ?<div>
?? ??? ??? ?<span onClick={param.getInfo}>調(diào)用父組件函數(shù)</span>
?? ??? ?</div>
?? ?}
}子組件調(diào)用父組件函數(shù),可以向父組件傳參,刷新父組件信息
2.父組件調(diào)用子組件函數(shù)方法
//父組件
//需要引入useRef
import {useRef} from 'react'
let Father=()=>{
?? ?const childRef=useRef();
?? ?let onClick=()=>{
?? ??? ?childRef.current.getInfo();
?? ?}
?? ?return ()=>{
?? ??? ?<div>
?? ??? ??? ?<Children?
?? ??? ??? ??? ?ref={childRef}
?? ??? ??? ?/>
?? ??? ??? ?<span onClick={onClick}>調(diào)用子組件函數(shù)</span>
?? ??? ?</div>
?? ?}
}//子組件?
//需要引入useImperativeHandle,forwardRef
import {useImperativeHandle,forwardRef} from 'react'
let Children=(ref)=>{
?? ?useImperativeHandle(ref, () => ({
? ? ? ? getInfo:()=>{
? ? ? ? ? ? //需要處理的數(shù)據(jù)
? ? ? ? }
? ? }))
?? ?return ()=>{
?? ??? ?<div></div>
?? ?}
}
Children = forwardRef(Children);useImperativeHandle 需要配合著 forwardRef 使用,要不就會出現(xiàn)以下警告
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
React Hook 父子組件傳值
我司現(xiàn)在技術(shù)棧是react,用的是開箱即用的pro,我個人習慣用函數(shù)式組件,所以用hook比較多?,F(xiàn)在寫個父子組件傳值的示例,希望能幫助到你。
父組件
import React, { useState,createContext} from "react";
import Counter from './index1'
const myContext = createContext();
function App() {
? const [count, setCount] = useState(0);
? return (
? ? <div>
? ? ? <h4>我是父組件</h4>
? ? ? <p>點擊了 {count} 次!</p>
? ? ? <button
? ? ? ? onClick={() => {
? ? ? ? ? setCount(count + 1);
? ? ? ? }}
? ? ? >
? ? ? ? 點我
? ? ? </button>
? ? ? {/* 關(guān)鍵代碼 */}
? ? ? {/* 提供器 */}
? ? ? <myContext.Provider value={count}>
? ? ? ? <Counter myContext={myContext} />
? ? ? </myContext.Provider>
? ? </div>
? );
}
export default App;子組件使用useContext ,來獲取父級組件傳遞過來的context值。
子組件
import React, { useContext} from 'react';
// 關(guān)鍵代碼
function Counter({myContext}) {
? ? const count = useContext(myContext); ?// 得到父組件傳的值
? ? return (
? ? ? ? <div>
? ? ? ? ? ? <h4>我是子組件</h4>
? ? ? ? ? ? <p>這是父組件傳過來的值:{count}</p>
? ? ? ? </div>
? ? )
}
export default Counter;以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
React前端解鏈表數(shù)據(jù)結(jié)構(gòu)示例詳解
這篇文章主要為大家介紹了React前端解鏈表數(shù)據(jù)結(jié)構(gòu)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
React中的useState和setState的執(zhí)行機制詳解
這篇文章主要介紹了React中的useState和setState的執(zhí)行機制,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
React中實現(xiàn)父組件調(diào)用子組件的三種方法
在React中,組件之間的通信是一個常見的需求,有時,我們需要從父組件調(diào)用子組件的方法,這可以通過幾種不同的方式實現(xiàn),需要的朋友可以參考下2024-04-04
React Native:react-native-code-push報錯的解決
這篇文章主要介紹了React Native:react-native-code-push報錯的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10

