Refs


ReactNative系列-文章

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。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值