react中ref怎么用


本文摘自PHP中文网,作者藏色散人,侵删。

react中ref的使用方法:1、通过回调函数形式进行使用,代码如“export default class UserAdd extends Component{...}”;2、通过string形式进行使用,代码如“export...”。

本教程操作环境:Windows7系统、react16版,该方法适用于所有品牌电脑。

推荐:《javascript基础教程》

react中ref的两种使用方法

ref一共有两种使用方式

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

  • string形式

第一种 回调函数形式

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

组件渲染后

组件卸载后

ref改变后

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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>

        )

    }

  

}

更多编程相关知识,请访问:编程学习!!

以上就是react中ref怎么用的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

React初级基础面试题(分享)

React完成一个图片轮播组件

React中如何引入css样式

angular与angularjs、React和vue的简单对比

webstorm写React出现报错怎么办

React中图片用什么标签

React怎么循环map

大型项目为什么要用React

React如何写点击事件

React中swiper插件如何使用?

更多相关阅读请进入《React》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...