【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>

转载于:https://www.cnblogs.com/huxiaoyun90/p/5657937.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值