React Ref

Ref 是什么

Ref 是 Reference 的缩写,就是引用的意思

与 state 不同的是,ref 不是每次 render 一个版本,它类似于一个全局变量

  1. 每次渲染 ref 返回值都不变
  2. ref 变化不会造成 re-render

ref 发生变化应该作为 Side Effect(因为它会影响下次渲染),所以不应该在 render 阶段更新 current 属性。

Ref 的目的

  1. 访问 DOM 元素
  2. 作为一个变量

Ref 的使用

class 组件使用 createRef 创建 Ref 实例:

class AutoFocusTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();
  }

  componentDidMount() {
    this.textInput.current.focusTextInput();
  }

  render() {
    return <CustomTextInput ref={this.textInput} />;
  }
}

function 组件使用 useRef HOOK 声明 Ref:

function CustomTextInput(props) {
  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>
  );
}

Ref 与 render

ref.current 发生变化不会造成 re-render

不应该在 render 阶段更新 ref.current 属性,ref.current 发生变化应该作为 Side Effect(影响下次渲染)

但是异步渲染的时候是可以的(更新 ref.current 属性)

Ref.current 不可作为 hooks 依赖项

Reactjs 并不会跟踪 ref.current 的变化,不要把 ref.current 作为其他 hooks(useMemo, useCallback, useEffect)依赖项

至于 Ref 本身,Ref 是不变的,更不能作为依赖项

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React中的ref是一个用来获取组件或DOM元素的返回值的属性。在React的生命周期函数中,你可以使用ref来强制组件重新渲染。 使用ref主要用来访问DOM元素,例如输入框、按钮等。使用ref可以实现获取输入框中的文本、获取按钮的值等操作。 ref有两种使用方式:string refs和function refs。 string refs是React较早时引入的一种使用方式,现在已经不再推荐使用。使用string refs需要给元素设置ref属性,值为字符串,然后将ref值赋值给一个成员变量。实例如下: ``` class MyComponent extends React.Component { componentDidMount() { console.log(this.inputRef.value); } render() { return( <input type="text" ref={(input) => this.inputRef = input} /> ) } } ``` function refs是现在推荐使用的一种方式,可以更好的控制和管理组件的引用。使用function refs需要将一个函数作为ref的值,这个函数会在组件挂载或卸载时被执行。实例如下: ``` class MyComponent extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } componentDidMount() { console.log(this.inputRef.current.value); } render() { return ( <input type="text" ref={this.inputRef} /> ) } } ``` 总结而言,ref是一个非常好用的工具,能够让开发人员更加方便的操作DOM元素,并且更好的控制和管理组件的引用。但是,需要注意的是,过度使用ref会使代码变得混乱难以维护,建议谨慎使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值