react获取input值的方法:1、通过event对象信息的方式获取input的值,语法如“inputChange(e){...}”;2、使用ref的方式获取input的值,语法如“this.setState({...})”。
本教程操作环境:windows7系统、react17.0.1版本,该方法适用于所有品牌电脑。
react 获取input 输入框的值
第一种方法:通过event对象信息的方式
第二种方法:使用ref的方式
通过event对象信息的方式this.inputChange(e)}/>
this.getInputValue} >获取input的值
inputChange(e){
alert(e.target.value)
this.setState({
username:e.target.value
})
}
getInputValue(){
alert(this.state.username)
}
使用ref的方式this.inputChange()}/>
this.getInputValue()} >获取input的值
inputChange(){
//获取dom节点元素
//1.添加ref属性
//2.使用this.refs.username获取dom节点
let val=this.refs.username.value;
this.setState({
username:val
})
}
getInputValue(){
console.log(this.state.username)
}
使用ref自定义一个属性,可以通过this.refs.属性名称.value获取内容。