React 中的 refs

Refs
Refs是什么


Refs 提供一种访问在render方法中DOM节点或者React元素的方式。

Refs作用


你可以通过它获得DOM节点或者React元素。一般用在处理焦点,文本选择,触发动画,触发方法等。例如,有一个CheckBox组件,你可以通过Refs获得该React元素,然后主动触发它的onClick方法:
 

<TouchableOpacity onPress={()=>{
    this.cb.onClick();
  }>
  <CheckBox ref={(c)=>{
      this.cb = c;
    }}
    onClick={()=>{
      console.log(‘clicked’);
    }}
  >
  </CheckBox>
</TouchableOpacity>

Refs的使用

创建 Refs

1. 使用 React.createRef() 创建 refs

class MyComponent extends React.Component {
  constructor(props) {
    this.myRef = React.createRef();
  }
  render() {
    return(
      <div ref={this.myRef}/>
    )
  }
}

可以使用current属性,对节点的引用进行访问。

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>
    );
  }
}

React 会在组件加载时将 DOM 元素传入 current 属性,在卸载时则会改回 null。ref 的更新会发生在componentDidMount 或 componentDidUpdate 生命周期钩子之前。

2. 回调形式创建 refs

<TouchableOpacity onPress={()=>{
    this.cb.onClick();
  }>
  <CheckBox ref={(c)=>{
      this.cb = c;
    }}
    onClick={()=>{
      console.log(‘clicked’);
    }}
  >
  </CheckBox>
</TouchableOpacity>

Refs知识点

  1. 不要过度使用Refs,如果可以通过声明实现,则尽量避免使用refs;
  2. 不能在函数式组件上使用ref属性(就是function定义的组件,不是class),因为它们没有实例;
  3. ref 的更新会发生在componentDidMount 或 componentDidUpdate 生命周期钩子之前。所以不能在组件卸载的时候直接使用ref的react元素,React 会在组件卸载时将ref 改回 null。

猜你喜欢

转载自blog.csdn.net/m0_60237095/article/details/121087969