react中refs的作用是什么?有几种用法?

在 React 中,ref 是用来获取组件或 DOM 元素的引用的一种方式。ref 可以在组件挂载后被访问,并且允许您从组件中访问底层的 DOM 元素或组件实例。

ref 有两种用法:字符串 ref 和回调函数 ref。

  1. 字符串 ref(string refs)是一种早期的使用 ref 的方式。它通过设置 ref 属性为一个字符串,将 ref 关联到一个 DOM 元素或组件实例上。然后可以通过 this.refs 获取这个 ref。
    class MyComponent extends React.Component {
      componentDidMount() {
        const input = this.refs.myInput;
        input.focus();
      }
    
      render() {
        return(
          <div>
            <input type="text" ref="myInput" />
          </div>
        );
      }
    }
    
  2. 回调函数 ref(callback refs)是一种现代而常用的使用 ref 的方式。它通过设置 ref 属性为一个回调函数,将 ref 关联到一个 DOM 元素或组件实例上。当组件挂载或卸载时,React 会调用这个回调函数,并将 DOM 元素或组件实例作为参数传递进去。
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.inputRef = null;
      }
    
      componentDidMount() {
        this.inputRef.focus();
      }
    
      setInputRef = (ref) => {
        this.inputRef = ref;
      };
    
      render() {
        return (
          <div>
            <input type="text" ref={this.setInputRef} />
          </div>
        );
      }
    }
    

    需要注意的是,字符串 ref 在 React v16.3 之后被废弃了,建议使用回调函数 ref。此外,对于函数组件,可以使用 useRef Hook 来获取组件或 DOM 元素的引用

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值