在子组件回调后在父视图中呈现另一个视图
Rendering another view in Parent after Child component callback
我真的不知道该怎么做,我有一个 login.tsx 文件和 App.tsx 文件:
在 login.tsx 我有:
const Login = () => {
const classes = useStyles();
const [state, dispatch] = useReducer(reducer, initialState);
[...]
const handleLogin = () => {
if (state.password === 'password' && state.username.length > 2) {
dispatch({
type: 'loginSuccess',
payload: 'Login Successfully'
});
// here I want to add the callback to the parent function App
} else {
dispatch({
type: 'loginFailed',
payload: 'Username too short or incorrect password'
});
}
};
并在 App.tsx 中:
if (true) { // replace true with the callback from the child
return <Login />
}
return ( // (else)
<div className="App"> // the other view we want once logged in successfully
[...]
因此,一旦用户登录,它就会自动呈现另一个视图。很抱歉这个非常愚蠢的问题,我对 React 不是很有经验。
注意:我知道这不是安全的方式(登录验证应该使用 JWT/OAuth 等)。
您的 App.tsx 中需要一个状态,负责跟踪要渲染的组件,例如:const [showLogin, setShowLogin] = useState(true);
。
然后在 if/else 语句中使用 showLogin
变量。
您还需要将一个函数作为 prop 传递给您的登录组件,该组件将在登录完成后更新 showLogin
,如下所示:
<Login onLogin={() => setShowLogin(false)} />
.
然后,在您的 handleLogin 函数中,调用传递给您的登录组件的 onLogin 函数。
从 OP 编辑:
还稍微将代码更改为 const Login = (props: {onLogin: any }) => {
并致电 props.onLogin();
我真的不知道该怎么做,我有一个 login.tsx 文件和 App.tsx 文件:
在 login.tsx 我有:
const Login = () => {
const classes = useStyles();
const [state, dispatch] = useReducer(reducer, initialState);
[...]
const handleLogin = () => {
if (state.password === 'password' && state.username.length > 2) {
dispatch({
type: 'loginSuccess',
payload: 'Login Successfully'
});
// here I want to add the callback to the parent function App
} else {
dispatch({
type: 'loginFailed',
payload: 'Username too short or incorrect password'
});
}
};
并在 App.tsx 中:
if (true) { // replace true with the callback from the child
return <Login />
}
return ( // (else)
<div className="App"> // the other view we want once logged in successfully
[...]
因此,一旦用户登录,它就会自动呈现另一个视图。很抱歉这个非常愚蠢的问题,我对 React 不是很有经验。
注意:我知道这不是安全的方式(登录验证应该使用 JWT/OAuth 等)。
您的 App.tsx 中需要一个状态,负责跟踪要渲染的组件,例如:const [showLogin, setShowLogin] = useState(true);
。
然后在 if/else 语句中使用 showLogin
变量。
您还需要将一个函数作为 prop 传递给您的登录组件,该组件将在登录完成后更新 showLogin
,如下所示:
<Login onLogin={() => setShowLogin(false)} />
.
然后,在您的 handleLogin 函数中,调用传递给您的登录组件的 onLogin 函数。
从 OP 编辑:
还稍微将代码更改为 const Login = (props: {onLogin: any }) => {
并致电 props.onLogin();