ref

作者: 章鱼要回家 | 来源:发表于2019-09-25 15:47 被阅读0次

本文转自:
https://blog.csdn.net/qq_20069429/article/details/81750070

ref一共有两种使用方式:
  • 回调函数形式(官方推荐)
  • string形式
回调函数形式

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

  • 组件渲染后
  • 组件卸载后
  • ref改变后
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>
        )
    }
}
字符串的形式 使用时用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>
        )
    }
}

相关文章

网友评论

      本文标题:ref

      本文链接:https://www.haomeiwen.com/subject/rmfwuctx.html