Home > Web Front-end > JS Tutorial > body text

How to get the value of input in react

藏色散人
Release: 2023-01-04 09:36:40
Original
10925 people have browsed it

React method to obtain the input value: 1. Obtain the input value through event object information, with syntax such as "inputChange(e){...}"; 2. Use ref to obtain the input value , the syntax is such as "this.setState({...})".

How to get the value of input in react

The operating environment of this tutorial: windows7 system, react17.0.1 version, thinkpad t480 computer.

Recommendation: "javascript basic tutorial"

react Get the value of the input input box

The first method: through The method of event object information

The second method: the method of using ref

The method of event object information

<input onChange={(e)=>this.inputChange(e)}/>
<button onClick={()=>this.getInputValue} >获取input的值</button>
inputChange(e){
alert(e.target.value)
this.setState({
username:e.target.value
})
}
getInputValue(){
alert(this.state.username)
}
Copy after login

The method of using ref

<input ref=&#39;username&#39; onChange={()=>this.inputChange()}/>
<button onClick={()=>this.getInputValue()} >获取input的值</button>
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)
}
Copy after login

Use ref to customize an attribute, and you can get the content through this.refs.property name.value.

The above is the detailed content of How to get the value of input in react. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!