日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

React?Hook?父子組件相互調(diào)用函數(shù)方式_React

作者:xffff00 ? 更新時間: 2022-11-07 編程語言

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,我個人習(xí)慣用函數(shù)式組件,所以用hook比較多。現(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;

原文鏈接:https://blog.csdn.net/xffff00/article/details/106664573

欄目分類
最近更新