react学习日志3
来源:互联网 发布:java接收上传图片表单 编辑:程序博客网 时间:2024/06/05 19:47
demo2
1.分析案例
以下这个demo来自https://github.com/liwudi
作为自己学习给自己分析一下代码
这是一个简单的路由功能的Redirect 的demo
实现结果为,当点击非公开页面是,由点击的路由跳到判断是否登陆的路由,代码 如下
App.js
render() { return( <Router> <div> <AuthButton isLogin={this.state.isLogin} /> <ul> <li><Link to="/public">公开界面</Link></li> <li><Link to="/private">非公开界面</Link></li> </ul> <Route path="/public" component={Public}/> <Route path="/login" component={Login} /> <Route path="/private" render={()=>( this.state.isLogin?( <Private /> ):( <Redirect to="/login" /> ) )}/> </div> </Router> )}当点击非公开页面时,判断isLogin的状态,只有当true的时候才会显示正确的页面。
Login组件
import React, { Component } from 'react';import LoginBtn from './LoginBtn';export default class Login extends Component { constructor(props){ super(props); console.log(this.props); this.state = { redirectToReferrer: false, } } login(){ this.setState({ redirectToReferrer: true, }); localStorage.setItem("isLogins", true); } render(){ return ( <div>若想访问,请先登录<LoginBtn text = "登录" click={this.login.bind(this)}/></div> ) }}当点击登陆时,调用LoginBtn,在缓存里设置isLogins状态值
LoginBtn组件
import React, { Component } from 'react';export default class LoginBtn extends Component { constructor(props){ super(props); } render(){ return ( <button onClick = { this.props.click }>{this.props.text}</button> ) }}该组件为一个button按钮,按钮上的值为props.text
AuthButton
import React, { Component } from 'react';import LoginBtn from './LoginBtn';export default class AuthButton extends Component { constructor(props){ super(props); } exit(){ localStorage.setItem("isLogins", false); console.log(this.props); } render(){ return ( (this.props.isLogin)?<p>欢迎!登出<LoginBtn text="退出" click={this.exit.bind(this)}/></p>:<p>请您先登陆</p> ) }}该组件为点击登出时,将缓存里的isLogins重新赋值为false
2.修改代码
(1)为login添加登陆判断条件,涉及知识点,外部获取input的value值
a. 为login组件添加改变框内值的方法,通过监测value值,与key进行匹配
change=(e)=>{ this.setState({value: e.target.value});};react 表单知识后续再进行学习,现在,继续学习react routerif(this.state.value==this.state.key){ localStorage.setItem("isLogins", true);}<input onChange={this.change} value={this.state.value}/>
阅读全文
0 0
- react学习日志3
- react学习日志1
- react学习日志2
- react学习日志4
- [react native]学习日志---es6语法学习
- React学习笔记(3)
- react redux 学习3
- react学习总结3--React-Router
- react 学习
- react学习
- react学习
- react学习
- react 学习
- React学习
- React学习
- react学习
- React学习
- react学习
- layUI rable 初始化加载数据、数据刷新表格、传参数
- BootstrapValidator.js 插件针对表单的验证
- c++中内存拷贝函数(C++ memcpy)详解
- 洛谷-摆花-动态规划
- 架构师之路(1)秒杀系统架构优化思路
- react学习日志3
- Python学习资料
- C++联合体
- HibernateDaoSupport详解
- [来源未知][小学奥数]组合数取模
- Node.js 2小时爬取驴妈妈8W+条旅游数据
- 提取深度网络某一层特征
- Nginx 与 阿帕奇 配合使用配置记录(实现 多个 tomcat 多个 php网站 共存)。
- Android studio Error converting LogicalPosition: (59, 0); leans forward to visual position