当前位置: 代码迷 >> 综合 >> react中ref的两种使用方法
  详细解决方案

react中ref的两种使用方法

热度:43   发布时间:2023-10-27 14:46:14.0

ref一共有两种使用方式

  • 回调函数形式(官方推荐)
  • string形式

第一种 回调函数形式

回调函数形式一共有三种触发方式

  • 组件渲染后
  • 组件卸载后
  • ref改变后
import React,{Component} from 'react'
export default class UserAdd extends Component{constructor(){super();}handleSubmit=()=>{let name=this.inputName.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={inputName => { this.inputName = inputName }}/></div><div className="from-group"><input type="submit" className="btn btn-primary"/></div></form>)}} 

第二种 字符串的形式 使用时用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>)}} 

 

  相关解决方案