zoukankan      html  css  js  c++  java
  • 受控组件和非受控组件

    受控组件处理表单数据是交给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'))
    
  • 相关阅读:
    AT89C51单片机的主要组成结构
    Keil C51的库函数
    Keil C51程序设计
    bootchart 使用说明及代码分析
    [转]android下编译libusb和libhackrf
    [转]Android系统编译过程分析
    [转]Android U 盘功能实现和分析
    [转]深入理解Android之设备加密Device Encryption
    [转]Makefile 中:= ?= += =的区别
    [转]Makefile中常用的函数
  • 原文地址:https://www.cnblogs.com/nianzhilian/p/13362169.html
Copyright © 2011-2022 走看看