React---- ref

本文详细介绍了React中三种创建和使用ref的方法:React.createRef(),ref属性赋值以及ref回调函数。分别阐述了它们在HTML元素和自定义组件上的应用,以及如何通过ref实现子组件向父组件的通信。

方法一:React.createRef()

  1. 用于HTML元素上 其current 属性 值为 DOM 元素
  2. 自定义 class 组件 值为 组件的挂载实例
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  getRef(){
  	const node = this.myRef.current;
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

方法二:ref属性赋值 不建议使用,有可能会存在 一些问题,可能会被移除

  1. 用于HTML元素上 其this.refs.名 值为 DOM 元素
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  getRef(){
  	const node = this.refs.myRef;
  }
  render() {
    return <div ref='myRef' />;
  }
}

方法三:Refs回调
使用 ref 回调函数,在实例的属性中存储对 DOM 节点的引用。

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);

    this.textInput = null;

    this.setTextInputRef = element => {
      this.textInput = element;
    };

    this.focusTextInput = () => {
      // 使用原生 DOM API 使 text 输入框获得焦点
      if (this.textInput) this.textInput.focus();
    };
  }

  componentDidMount() {
    // 组件挂载后,让文本框自动获得焦点
    this.focusTextInput();
  }

  render() {
    // 使用 `ref` 的回调函数将 text 输入框 DOM 节点的引用存储到 React
    // 实例上(比如 this.textInput)
    return (
      <div>
        <input
          type="text"
          ref={this.setTextInputRef}
        />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

这种方式还可以实现 子组件向父组件暴露其ref

function CustomTextInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  );
}

class Parent extends React.Component {
  render() {
    return (
      <CustomTextInput
        inputRef={el => this.inputElement = el}
      />
    );
  }
}
// this.inputElement 储存了子组件input元素
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值