受控组件

执行的函数无参数

import React , {Component} from 'react';
class App extends Component{
    constructor(){
        super();
        this.state = {
            inputvalue:''
        }
    }

    handelChange(event){
        this.setState({
            inputvalue:event.target.value
        })
    }

    render(){
        return(
            <div>
                <input type="text" onChange={this.handelChange.bind(this)}/>
            </div>
        )
    }
}

export default App

执行的函数有参数

若执行的函数有参数,在React中,需要将event参数放在最后

import React , {Component} from 'react';
class App extends Component{
    constructor(){
        super();
        this.state = {
            inputvalue:''
        }
    }

    handelChange(a,event){
        this.setState({
            [a]:event.target.value
        })
    }

    render(){
        return(
            <div>
                <input type="text" onChange={this.handelChange.bind(this,'inputvalue')}/>
            </div>
        )
    }
}

export default App

非受控组件

使用ref获取真实DOM的值

import React , {Component} from 'react';
class App extends Component{
    constructor(){
        super()
        this.state = {
            inputvalue: ''
        }
    }
    handelChange(){
        let value=this.refs.input.value
        this.setState({
            inputvalue: value
        })
    }

    render(){
        return(
            <div>
                <input type="text" ref='input' onChange = {this.handelChange.bind(this)}/>
                <p>{this.state.inputvalue}</p>
            </div>
        )
    }
}

export default App
Last modification:October 28, 2019
If you think my article is useful to you, please feel free to appreciate