javascript - React Context API 和组件方法
问题描述
我关注了一些在线示例,它们在 Context 中有一个计数器和一个增量函数,在一个遥远的组件上,调用增量方法并显示结果。一切都很好,但是......我正在尝试对此进行扩展并创建一个登录框,它设置一个 isAthenticated 标志。
我有一个非常基本的背景:
import React from 'react';
const Context = React.createContext();
export class Provider extends React.Component {
state = {
isAuthenticated: false,
user: {
name: "Craig",
email: "craig@here.com"
},
changeEmail: (newEmail) => {
let user = this.state.user;
user.email = newEmail;
console.log(user);
this.setState({ user: user})
},
changeAuthenticated: () => {
this.setState ({ isAuthenticated: !this.state.isAuthenticated });
}
}
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
)
}
}
export const Consumer = Context.Consumer;
在其中,我允许用户更改电子邮件,并更改 isAuthenticated 状态。
我的组件(删除样式的东西)看起来像这样:
import React from 'react';
import { Input, Label, Button, Container } from 'reactstrap';
import { Consumer } from '../context';
class Login extends React.Component {
render() {
return (
<Consumer>
{value => {
return (
<Container style={containerStyle} >
<div style={loginBoxStyle}>
<div>
<h3>Login</h3>
</div>
<div style={loginBoxFieldsStyle}>
<div style={loginBoxFieldStyle}>
<div style={loginBoxLabelStyle}>
<Label for="email">Email:</Label>
</div>
<div style={loginBoxLabelStyle}>
<Input type="email" name="email" id="email" placeholder="Your Email" value={value.user.email} onChange={e=>value.changeEmail(e.target.value)} />
</div>
</div>
</div>
<div style={loginBoxFieldsStyle}>
<div style={loginBoxFieldStyle}>
<div style={loginBoxLabelStyle}>
<Label for="password">Password:</Label>
</div>
<div style={loginBoxLabelStyle}>
<Input type="password" name="password" id="password" placeholder="Your Password" />
</div>
</div>
</div>
<div style={loginBoxButtonStyle}>
<Button color="info" onClick={value.changeAuthenticated}>Login</Button>
</div>
</div>
</Container>
)}
}
</Consumer>
)
}
}
export default Login;
因此,当我更改电子邮件时,上下文状态会更新。现在,当我单击登录按钮时,它只是切换 IsAuthenticated。
我不希望在我在电子邮件框中键入时更新状态。我更愿意在单击登录按钮时更新状态。所以我觉得我需要一个本地组件状态,或者其他东西,当我在文本框中编辑数据时,它会更新该状态。然后在我单击登录时更新上下文。
但是...我如何设置状态?“值”(来自上下文)仅在渲染内部可用。我需要在渲染之外设置我的组件状态。那么我将如何实现这一目标呢?
我的登录按钮 onClick 还应该触发一个具有所有验证等的本地方法,然后更新我的路由以重定向到成功的页面。但随后它需要从标签外部访问 Context.UpdateMethod。不知道如何实现这一点。
解决方案
您可能应该只创建一个子组件,然后使用道具来初始化状态。
class Login extends React.Component {
render() {
return (
<Consumer>
{value => (
<Container style={containerStyle}>
<SubComponent
changeAuthenticated={value.changeAuthenticated}
// ...etc
推荐阅读
- javascript - 如何在 pupeteer 中模拟拖放动作
- oauth - 流明模拟/临时重新登录用户
- python - pandas read_excel 共享违规
- google-cloud-firestore - Firestore 安全规则奇怪的行为
- php - 在 laravel 中使用 composer 安装 Mailgun\Bogardo 包时出现问题
- sql-server - 如何使用 freetds 为 sphinx 配置 unixODBC 驱动程序。错误:来源:未知类型“odbc”;跳过
- php - BaseDN 语法与 LDAP 一起使用
- email - 如果请求 AD 字段为空,我如何不打印字符串
- javascript - React-bootstrap ToggleButtonGroup 在调用时使用旧值
- java - 如何在 Tensorflow 移动 Android 应用程序上使用预训练模型?