【发布时间】:2020-03-31 00:37:13
【问题描述】:
我觉得这很简单,只是我缺乏使用 react.js 的经验,但我有我的 app.js 文件,它的状态值为 isUserLoggedIn,我将其传递到我的登录.js 文件作为道具。
这些值正在进入登录页面,因为我可以在那里使用条件来相应地呈现或 console.log。
但是,我似乎无法弄清楚如何(使用 Login.js 中的 handleSubmit 函数)将 props 中的 loggedIn 值设置为 true 并传回 app.js 文件。
我正在使用它在 app.js 中进行有条件的渲染,所以我需要做的就是能够更改 login.js 中loggedIn 的值并将其传递回app.js。
我该怎么做?
App.js
class App extends React.Component {
state = {
isUserLoggedIn: false
};
render() {
return (
<Router>
<Row className={css(styles.container)}>
<Column flexGrow={1} className={css(styles.mainBlock)}>
<div className={css(styles.content)}>
<Switch>
<Route path="/" exact component={(props) => <Login {...props} loggedIn = {this.state.isUserLoggedIn}/>} />
</Switch>
</div>
</Column>
</Row>
</Router>
);
}
}
}
export default App;
登录.js
import React, { useState } from "react";
import { Button, FormGroup, FormControl, FormLabel } from "react-bootstrap";
import "./Login.css";
export default function Login(props) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
function validateForm() {
return email.length > 0 && password.length > 0;
}
async function handleSubmit(event) {
event.preventDefault();
try{
props.history.push("/");
}catch (e) {
alert(e.message);
}
}
return(
<div className="Login">
<form onSubmit={handleSubmit}>
<FormGroup controlId="email" bsSize="large">
<FormLabel>Email</FormLabel>
<FormControl
autoFocus
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
</FormGroup>
<FormGroup controlId="password" bsSize="large">
<FormLabel>Password</FormLabel>
<FormControl
value={password}
onChange={e => setPassword(e.target.value)}
type="password"
/>
</FormGroup>
<Button bsSize="large" disabled={!validateForm()} type="submit">
Login
</Button>
</form>
</div>
);
}
【问题讨论】:
-
向下传递一个回调,该回调具有对组件的引用,该组件具有状态的 setState 方法,它通过更新调用该方法。这在 React 文档中有介绍。
-
@JaredSmith 谢谢,我现在就去看看。因此,我会将来自 app.js 的回调传递给我已经传递道具的组件中的 Login.js。然后我可以在我的 login.js 函数中设置相同值的状态?
标签: javascript reactjs