React Hook 父子组件相互调用函数
1.子组件调用父组件函数方法
//父组件 let Father=()=>{ ?? ?let getInfo=()=>{ ?? ??? ? ?? ?} ?? ?return ()=>{ ?? ??? ?<div> ?? ??? ??? ?<Children? ?? ??? ??? ??? ?getInfo={getInfo} ?? ??? ??? ?/> ?? ??? ?</div> ?? ?} }
//子组件 let Children=(param)=>{ ?? ?return ()=>{ ?? ??? ?<div> ?? ??? ??? ?<span onClick={param.getInfo}>调用父组件函数</span> ?? ??? ?</div> ?? ?} }
子组件调用父组件函数,可以向父组件传参,刷新父组件信息
2.父组件调用子组件函数方法
//父组件 //需要引入useRef import {useRef} from 'react' let Father=()=>{ ?? ?const childRef=useRef(); ?? ?let onClick=()=>{ ?? ??? ?childRef.current.getInfo(); ?? ?} ?? ?return ()=>{ ?? ??? ?<div> ?? ??? ??? ?<Children? ?? ??? ??? ??? ?ref={childRef} ?? ??? ??? ?/> ?? ??? ??? ?<span onClick={onClick}>调用子组件函数</span> ?? ??? ?</div> ?? ?} }
//子组件? //需要引入useImperativeHandle,forwardRef import {useImperativeHandle,forwardRef} from 'react' let Children=(ref)=>{ ?? ?useImperativeHandle(ref, () => ({ ? ? ? ? getInfo:()=>{ ? ? ? ? ? ? //需要处理的数据 ? ? ? ? } ? ? })) ?? ?return ()=>{ ?? ??? ?<div></div> ?? ?} } Children = forwardRef(Children);
useImperativeHandle 需要配合着 forwardRef 使用,要不就会出现以下警告
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
React Hook 父子组件传值
我司现在技术栈是react,用的是开箱即用的pro,我个人习惯用函数式组件,所以用hook比较多。现在写个父子组件传值的示例,希望能帮助到你。
父组件
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> ? ? ? {/* 关键代码 */} ? ? ? {/* 提供器 */} ? ? ? <myContext.Provider value={count}> ? ? ? ? <Counter myContext={myContext} /> ? ? ? </myContext.Provider> ? ? </div> ? ); } export default App;
子组件使用useContext ,来获取父级组件传递过来的context值。
子组件
import React, { useContext} from 'react'; // 关键代码 function Counter({myContext}) { ? ? const count = useContext(myContext); ?// 得到父组件传的值 ? ? return ( ? ? ? ? <div> ? ? ? ? ? ? <h4>我是子组件</h4> ? ? ? ? ? ? <p>这是父组件传过来的值:{count}</p> ? ? ? ? </div> ? ? ) } export default Counter;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于React Hook 父子组件相互调用函数方式的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did120802