• 受控组件和非受控组件


    受控组件处理表单数据是交给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'))
    
  • 相关阅读:
    标记不同浏览器的Burp Suite 插件
    60%配列机械键盘客制化清单
    配合mitmproxy使用自动化工具测试阿里云API网关接口
    CORS & CSP笔记
    fmex挂单挖矿
    使用SPLUNK进行简单Threat Hunting
    Mac最新系统bssdb BUG
    技巧之如何快速使用websocket来监控标准输出
    币早知道夺宝题--以太坊题解题方法
    发行NEO的NEP-5合约代币
  • 原文地址:https://www.cnblogs.com/nianzhilian/p/13362169.html
Copyright © 2020-2023  润新知