【JAVASCRIPT】React 学习 - 登录实战

摘要

实现一个登录的react 组件, 包含组件更新、ajax 交互、渲染新组建。

代码

<head>
	<meta charset="utf-8">
	<title></title>
    <script src="../build/react.js"></script>
    <script src="../build/react-dom.js"></script>
    <script src="../build/browser.min.js"></script>
    <script src="../build/jquery.min.js"></script>
</head>
<body>
<div id="loginForm"></div>
<script type="text/babel">

var LoginForm = React.createClass({
	getInitialState: function(){
		return {
			username: '',
			password: '',
			info: ''
		};
	},
	handlerNameChange: function(event) {
		var name = event.target.value;
		// 验证name 有效性
		if (name.length < 2) {
			this.setState({name: name, info: '名称长度过短'});
		}else {
			this.setState({name: name, info: ''});
		}
	},
	handlePasswordChange: function(event) {
		var password = event.target.value;
		// 验证password是否有效
		if (password.length < 2) {
			this.setState({password: password, info: '密码长度过短'});
		}else {
			this.setState({password: password, info: ''});
		}
	},
	handlerLogin: function(event) {
		var that = this;
		var name = this.state.name;
		var password = this.state.password;
		if ((name.length < 2) || (password.length < 2)) {
			that.setState({info: '名称/密码长度过短'});
		}else {
			// 模拟发送ajax 请求
			$.ajax({
				url: 'https://api.github.com/search/repositories?q=javascript&sort=stars',
				type: 'get',
			}).done(function(data) {
				var incomplete_results = data.incomplete_results;
				if(!incomplete_results) {
					// that.setState({info: '登录成功'});
					ReactDOM.render(<SuccessForm/>, document.getElementById('loginForm'));
				}else {
					that.setState({info: '登录失败,请检查名称or密码是否正确'});
				}
			});
		}
	},
	render: function(){
		return (
			<div>
				<div>姓名:<input type="text"  value={this.state.name} onChange={this.handlerNameChange}/></div>
				<div>密码:<input type="password" value={this.state.password} onChange={this.handlePasswordChange} /></div>
				<div><span>{this.state.info}</span><button onClick={this.handlerLogin} type="button">登录</button></div>
			</div>
		);
	}
});

ReactDOM.render(<LoginForm/>, document.getElementById('loginForm'));


var SuccessForm = React.createClass({
	render: function() {
		return (
			<div>Success!</div>
		);
	}
});
</script>

posted @ 2016-07-10 16:21  空城夕  阅读(257)  评论(0编辑  收藏  举报