受控组件和非受控组件

受控组件处理表单数据是交给react内部的状态来处理,而非受控组件可以通过ref 交给dom来处理

1、受控组件的表单处理

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types';

class App extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            value:'blob'
        }
        this.changeHandle = this.changeHandle.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
    }
    changeHandle(event){
        let val = event.target.value
        this.setState((state)=>({
            value:val
        }))
    }
    handleSubmit(event){
        alert('您输入的是'+this.state.value)
        event.preventDefault();  
    }
    render(){
        return (
            <form onSubmit={this.handleSubmit}>
                <input placeholder="请输入" value={this.state.value} onChange={this.changeHandle} />
                <input type="submit" value="Submit" />
            </form>
        )
    }
}

ReactDOM.render(<App />,document.getElementById('root'))

 2、非受控组件的表单处理

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types';

class App extends React.Component{
    constructor(props){
        super(props)
        this.input = React.createRef()
        this.handleSubmit = this.handleSubmit.bind(this)
    }
    handleSubmit(event){
        alert('您输入的是'+this.input.current.value)
        event.preventDefault();  
    }
    render(){
        return (
            <form onSubmit={this.handleSubmit}>
                <input ref={this.input} placeholder="请输入" defaultValue="blob" />
                <input type="submit" value="Submit" />
            </form>
        )
    }
}

ReactDOM.render(<App />,document.getElementById('root'))

 

posted @ 2020-07-22 17:54  飞奔的龟龟  阅读(216)  评论(0编辑  收藏  举报