目录React Hook 父子组件相互调用函数1.子组件调用父组件函数方法2.父组件调用子组件函数方法React Hook 父子组件传值父组件子组件React Hook 父子组件相互
//父组件
let Father=()=>{
let getInfo=()=>{
}
return ()=>{
<div>
<Children
getInfo={getInfo}
/>
</div>
}
}
//子组件
let Children=(param)=>{
return ()=>{
<div>
<span onClick={param.getInfo}>调用父组件函数</span>
</div>
}
}
子组件调用父组件函数,可以向父组件传参,刷新父组件信息
//父组件
//需要引入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,用的是开箱即用的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;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: ReactHook父子组件相互调用函数方式
本文链接: https://www.lsjlt.com/news/167626.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0