关于react中的ref

本文详细介绍了React中ref的三种用法:字符串引用、回调函数和React.createRef(),并展示了如何通过ref获取DOM节点和组件实例。此外,还讨论了在react-redux中使用ref调用子组件方法的问题,以及在函数式组件中使用useRef的例子。
摘要由CSDN通过智能技术生成

关于react中的ref

ref有3种用法:
字符串
dom节点上使用,通过this.refs[refName]来引用真实的dom节点

<input ref="inputRef" /> //this.refs['inputRef']来访问

回调函数
React 支持给任意组件添加特殊属性。ref 属性接受一个回调函数,它在组件被加载或卸载时会立即执行。
当给 HTML 元素添加 ref 属性时,ref 回调接收了底层的 DOM 元素作为参数。
当给组件添加 ref 属性时,ref 回调接收当前组件实例作为参数。
当组件卸载的时候,会传入null
ref 回调会在componentDidMount 或 componentDidUpdate 这些生命周期回调之前执行。

<input ref={(input) => {this.textInput = input;}} type="text" />   //HTML 元素添加 ref 属性时
<CustomInput ref={(input) => {this.textInput = input;}} />   //组件添加 ref 属性

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

class Child extends React.Component{
    constructor(props){
        super(props);
        this.myRef=React.createRef();
    }
    componentDidMount(){
        console.log(this.myRef.current);
    }
    render(){
        return <input ref={this.myRef}/>
    }
}

(2)根据ref获取dom
React提供的这个ref属性,表示为对组件真正实例的引用,其实就是ReactDOM.render()返回的组件实例,但可以通过ReactDOM.findDOMNode(ref)来获取组件挂载后真正的dom节点

var Parent = React.createClass({
  render: function(){
    return (
      <div className = 'parent'>
        <Child ref = 'child'/>
      </div>
    )
  },
  componentDidMount(){
    console.log(this.refs.child); // 访问挂载在组件上ref
    console.log(ReactDOM.findDOMNode(this.refs.child)); // 访问真正的dom节点
  }
})

var Child = React.createClass({
  render: function() {
    return (
        <div ref="test">
          <a ref="update">更新</a>
        </div>
    );
  }
});

打印结果
在这里插入图片描述

(3)react-redux使用时利用ref调用子组件方法不可用报错
在使用react的时候,我们难免会在父组件中调用子组件的方法,我们常用ref调用子组件的方法

如下在父组件中调用子组件的写法

父组件

handleShowModalAdd = () => {
    this.add.handleToggle()//handleToggle为子组件中的方法
}

<SystemAdd ref={(el) => this.add = el}/>

但是当我们在子组件中使用redux的时候,由于使用connect对子组件进行了包装,会导致获取不到子组件中的方法

下面的是使用redux后的ref使用方法

父组件

handleShowModalAdd = () => {
    this.add.handleToggle()//handleToggle为子组件中的方法
}

<SystemAdd onRef={(ref) => this.add = ref }/>
子组件

componentDidMount(){
    this.props.onRef(this)//将组件实例this传递给onRef方法
}

在react的官方文档中也对函数式组件的ref狗子函数进行了实例

function CustomTextInput(props) {
  // 这里必须声明 textInput,这样 ref 才可以引用它
  const textInput = useRef(null);

  function handleClick() {
    textInput.current.focus();
  }

  return (
    <div>
      <input
        type="text"
        ref={textInput} />
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茂茂睡不醒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值