如何传递函数以链接React路由器V6中的组件
我想传递到链接组件的功能。我该怎么做?我尝试使用状态和使用状态,虽然它们在正常变量方面工作良好,但USEETOCE在尝试传递功能时会发送无效。
const function=someFunction(){}
<Link state={func:function} to="/LoginScreen" style={style.a} >
Login
</Link>
这行不通。
试图使用反应上下文的代码:
import React, { useState } from "react";
import { Link } from "react-router-dom";
const RefreshDisplayContext = React.createContext();
function Launchpad() {
const [launchpadState, updatelaunchpadState] = useState({
userIsLoggedIn: false
});
function refreshDisplay(event) {
updatelaunchpadState({ userIsLoggedIn: true });
}
return (
<RefreshDisplayContext.Provider value={refreshDisplay}>
<div>
{launchpadState.userIsLoggedIn ? (
<p>User is Logged In </p>
) : (
<p>User is Not Logged In </p>
)}
<Link to="login" state={launchpadState}>
Login via Child
</Link>
</div>
</RefreshDisplayContext.Provider>
);
}
export { Launchpad, RefreshDisplayContext };
import React, { useState } from "react";
import { RefreshDisplayContext } from "../routes/Launchpad";
function Login(props) {
const refreshDisplay = React.useContext(RefreshDisplayContext);
return (
<button
type="button"
onClick={() => refreshDisplay({ userIsLoggedIn: true })}
>
Login
</button>
);
}
export { Login };
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { Launchpad } from "./routes/Launchpad";
import { Login } from "./routes/Login";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<BrowserRouter>
<Routes>
<Route path="/" element={<Launchpad />} />
<Route path="/login" element={<Login />} />
</Routes>
</BrowserRouter>
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
。
代码问题的问题是,您仅在UI/ReactTree周围渲染
REFRESHDISPLAYCONTEXT
,即lainingpad
组件正在渲染 单击“/login”
的链接,然后该应用程序导航到该路由并渲染登录
,渲染的组件是 exterReact上下文正在尝试访问,并且由于也没有默认值,因此无法从未定义的上下文值访问
REFRESHDISPLAY
。解决方案
移动
REFRESHDISPLAYCONTEXT.PROVIDER
在ReactTree中更高,以便能够为所有消费者提供相同的上下文值。创建一个新文件来声明和导出上下文。
refreshdisplay.context.js
导入并包装您想要访问
refreshdisplayContext
的所有组件。index.js
更新消费者以访问提供的上下文值。
lainingpad
登录
Issue
The issue with the code is that you are only rendering the
RefreshDisplayContext
around the UI/ReactTree that theLaunchpad
component is rendering. When the link to"/login"
is clicked and the app navigates to that route and rendersLogin
, the component being rendered is outside theReact context it's trying to access, and since there's also no default value,
refreshDisplay
can't be accessed from the undefined context value.Solution
Move the
RefreshDisplayContext.Provider
higher in the ReactTree so that it is able to provide the same context value to all consumers.Create a new file to declare and export the context.
refreshDisplay.context.js
Import and wrap all the components you want to have access to the
RefreshDisplayContext
.index.js
Update the consumers to access the provided context value.
Launchpad
Login