首页 > 其他 > 详细

React 受控组件和非受控组件

时间:2021-07-08 10:16:36      阅读:25      评论:0      收藏:0      [点我收藏+]

需求

  • 创建一个表单组件然后提交

非受控组件

  • 现用现取
 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>
        )
    }
}

受控组件(推荐)

  • 随着你的输入将数据维护到状态里面
  • 不会过度使用ref
 // 创建组件
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>
        )
    }
}

React 受控组件和非受控组件

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!