Home > Article > Web Front-end > How to use ref in react
How to use ref in react: 1. Use it in the form of callback function, the code is like "export default class UserAdd extends Component{...}"; 2. Use it in the string form, the code is like "export ...".
The operating environment of this tutorial: Windows7 system, react16 version. This method is suitable for all brands of computers.
Recommended: "Javascript Basics Tutorial"
Two ways to use ref in react
There are two kinds of ref Usage
Callback function form (official recommendation)
string form
First type Callback function form
There are three triggering methods for the callback function form
After the component is rendered
After the component is unloaded
After the ref is changed
import React,{Component} from 'react' export default class UserAdd extends Component{ constructor(){ super(); } handleSubmit=()=>{ let name=this.name.value; console.log(name); } render(){ return( <form onSubmit={this.handleSubmit}> <div className="from-group"> <label htmlFor="name">姓名</label> <input type="text" className="form-control" ref={ref=>this.name=ref}/> </div> <div className="from-group"> <input type="submit" className="btn btn-primary"/> </div> </form> ) } }
When using the second string form, use this.refs.string
import React,{Component} from 'react' export default class UserAdd extends Component{ constructor(){ super(); } handleSubmit=()=>{ let name=this.refs.name.value; console.log(name); } render(){ return( <form onSubmit={this.handleSubmit}> <div className="from-group"> <label htmlFor="name">姓名</label> <input type="text" className="form-control" ref="name"/> </div> <div className="from-group"> <input type="submit" className="btn btn-primary"/> </div> </form> ) } }
For more programming-related knowledge, please visit: Programming Learning! !
The above is the detailed content of How to use ref in react. For more information, please follow other related articles on the PHP Chinese website!