react中的refs

文章类型:React

发布者:hp

发布时间:2024-07-29

一:原因

在react数据流中,props是组件交互唯一方式,在某些情况下,需要强制修改子组件,

主要是针对子组件是一个React组件实例或者DOM元素

二:是什么

Refs是React提供给我们安全访问DOM元素或者某个组件实例的句柄

我们可以为元素添加ref属性然后再回调函数接受该元素在DOM树中的句柄

该值会作为回调函数第一个参数返回


三:使用场景

1:管理焦点、文本选择、媒体播放

2:触发强制动画

3:集成第三方DOM库

四:怎么使用

1:使用

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // 创建一个 ref 来存储 textInput 的 DOM 元素
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // 直接使用原生 API 使 text 输入框获得焦点
    // 注意:我们通过 "current" 来访问 DOM 节点
    this.textInput.current.focus();
  }

  render() {
    // 告诉 React 我们想把 <input> ref 关联到
    // 构造器里创建的 `textInput` 上
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

2:说明

当 ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性。

当 ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例作为其 current 属性。

你不能在函数组件上使用 ref 属性,因为他们没有实例

五:注意

1:谨慎使用refs

2:更新过程会执行两次,第一次传入参数null,第二次传入参数DOM