react 中ref 属性的三种写法

react 中ref 属性的三种写法_第1张图片

目录

1. 字符串 ref

2.dom节点上使用回调函数ref

3.React.createRef()


1. 字符串 ref

最早的ref用法。(由于效率问题,现在官方不推荐使用这种写法。)

1.dom节点上使用,通过this.refs.xxxx来引用真实的dom节点

 

代码示例:

class test extends React.Component{
    constructor(props) {
        super(props);
    }
    showData = ()=>{
        const x = this.refs
        alert(x.value)
    }
    render() {
        return (
            
) } }

react 中ref 属性的三种写法_第2张图片

2.dom节点上使用回调函数ref

 {this.textInput = currentNode;}} type="text" />

简写:
 this.textInput = currentNode } type="text" />

其中的currentNode节点是,下图:

react 中ref 属性的三种写法_第3张图片

代码示例:

class test extends React.Component{
    constructor(props) {
        super(props);
    }
    showData = ()=>{
        const {input1} = this
        alert(input1.value)
    }
    saveInput =(currentNode)=>{
        this.input1 = currentNode
    }
    render() {
        return (
            
{this.input1 = currentNode}} type="text"/> //简写 this.input1 = currentNode} type="text"/>
) } }

3.React.createRef()

       在React 16.3版本后,使用此方法来创建ref。将其赋值给一个变量,通过ref挂载在dom节点或组件上,该ref的current属性 将能拿到dom节点或组件的实例


注意:React.createRef调用后可以返回一个容器,该容器可以存储被ref 所标识的节点

但是该容器是转人专用,一次只能存一个

myRef = React.createRef()

 代码示例:

class test extends React.Component{
    //React.createRef调用后可以返回一个容器,该容器可以存储被ref 所标识的节点
    myRef = React.createRef()
    constructor(props) {
        super(props);
    }
    showData = ()=>{
        alert(this.myRef.current.value)
    }
    saveInput =(currentNode)=>{
        this.input1 = currentNode
    }
    render() {
        return (
            
{/*{this.input1 = currentNode}} type="text"/>*/} {/*//简写*/} {/* this.input1 = currentNode} type="text"/>*/} {/**/}
) } }

你可能感兴趣的:(javascript,前端,react.js)