[react] react中什么是非控组件?

表单元素的value/checked值、onChange事件没有和组件的state存在绑定关联关系,如果需要获取表单元素的值,需要使用ref获取DOM,然后得到元素的值.demo如下:

import React from 'react';
class FormDemo extends React.Component {
    refUsername = React.createRef();
    refPassword = React.createRef();
    onSubmit = () => {
        const [
            username,
            password,
        ] = [
            this.refUsername.current.value,
            this.refPassword.current.value,
        ];
        console.log({
            username,
            password,
        })
    }
    render () {
        return (
            <div className="form">
                <p>
                    <span>用户名:</span>
                    <input ref={this.refUsername} name="username" />
                </p>
                <p>
                    <span>密码:</span>
                    <input ref={this.refPassword} name="password" />
                </p>
                <button onClick={this.onSubmit}>登录</button>
            </div>
        )
    }
}
export default FormDemo;

 个人简介

我是歌谣,欢迎和大家一起交流前后端知识。放弃很容易,
但坚持一定很酷。欢迎大家一起讨论













主目录

与歌谣一起通关前端面试题