如何在React+TypeScript中实现子组件返回父组件且不带查询参数
React+TypeScript 实现子组件返回父组件(无查询参数)方案
以下分两种常用场景给出实现代码:
场景1:使用react-router v6 做客户端路由
如果你的父子组件对应不同的页面路由,用该方案:
- 先确保你已经配置好父子组件的路由规则,比如父组件路由为
/parent,子组件路由为/child - 子组件实现代码:
import { useNavigate } from 'react-router-dom'; // 子组件props类型定义,按需扩展 interface ChildProps { // 其他自定义props } const ChildComponent: React.FC<ChildProps> = () => { const navigate = useNavigate(); const handleBack = () => { // 方案A:直接跳转至指定父组件路由,100%不会携带任何查询参数 // replace设为true可替换当前历史栈,避免用户点浏览器前进回到子组件 navigate('/parent', { replace: true }); // 方案B:等价于浏览器回退按钮,仅适合确定上一级页面就是父组件的场景 // navigate(-1); }; return ( <div> {/* 子组件原有业务内容 */} <button onClick={handleBack}>返回父组件</button> </div> ); }; export default ChildComponent;
场景2:无路由、用状态控制子组件显隐
如果父子组件在同一页面,通过状态控制是否渲染子组件,用该方案:
- 父组件传递关闭回调给子组件:
import { useState } from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { const [showChild, setShowChild] = useState(false); return ( <div> {/* 父组件原有业务内容 */} <button onClick={() => setShowChild(true)}>打开子组件</button> {showChild && <ChildComponent onBack={() => setShowChild(false)} />} </div> ); }; export default ParentComponent;
- 子组件接收回调触发返回:
interface ChildProps { // 关闭子组件的回调函数 onBack: () => void; // 其他自定义props } const ChildComponent: React.FC<ChildProps> = ({ onBack }) => { return ( <div> {/* 子组件原有业务内容 */} <button onClick={onBack}>返回父组件</button> </div> ); }; export default ChildComponent;
该场景下不会修改页面URL,天然不会携带查询参数。
内容的提问来源于stack exchange,提问作者DSR
相关产品推荐
相关产品推荐

