React 受控组件和非受控组件

时间:2021-07-08 10:16:36   收藏:0   阅读:25

需求

非受控组件

 class Login extends React.Component {
    // 表单提交
    handleSubmit = () => {
        const {username, password} = this;
        alert(`你输入的用户名是:${username.value},你输入的密码是:${password.value}`)
    }
    render() {
        return (
            <form action="#" onSubmit={this.handleSubmit}>
                用户名:<input ref={c => this.username = c} type="text" />
                密码:<input  ref={c => this.password = c} type="text" />
                <button>登录</button>
            </form>
        )
    }
}

受控组件(推荐)

 // 创建组件
class Login extends React.Component {
    state = {
        username: ‘‘, // 用户名
        password: ‘‘ // 密码
    }
    // 表单提交
    handleSubmit = () => {
        const { username, password } = this.state;
        alert(`你输入的用户名是:${username},你输入的密码是:${password}`)
    }
    charsetf = (dataType) => {
       return event => this.setState({[dataType]: event.target.value});
    }
    render() {
        return (
            <form action="#" onSubmit={this.handleSubmit}>
                用户名:<input onChange={this.charsetf(‘username‘)} type="text" />
                密码:<input onChange={this.charsetf(‘password‘)} type="text" />
                <button>登录</button>
            </form>
        )
    }
}

原文:https://www.cnblogs.com/landuo629/p/14984298.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!