refs是什么,如何使用,需要注意什么

Refs是什么?

Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。

何时适合使用 Refs?

  • 管理焦点,文本选择或媒体播放。
  • 触发强制动画
  • 集成第三方 DOM 库。

Refs有哪些使用方式?

  • 原生DOM元素上使用Ref
  • 类组件上使用Ref
  • 函数组件上使用Ref
  • 高阶组件上使用Ref
  • 函数组件使用HOOK useRef
import React, { Component, useRef } from "react";

export default class RefPage extends Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 0,
    };
    this.nameInputRef = React.createRef();
    this.passwordRef = React.createRef();
    this.ageInputRef = React.createRef();
    this.countryRef = React.createRef();
  }

  submit = (e) => {
    const name = this.nameInputRef.current.value;
    const password = this.passwordRef.current.getPassword();
    const age = this.ageInputRef.current.value;
    let country = this.countryRef.current.value;

    console.log("Submit", name, password, age, country); //, password, age, country, galaxy);
  };

  render() {
    const AgeInputRef = React.forwardRef(AgeInput);
    const HocCountry = hoc(CountryInput);

    return (
      <div>
        <div>
          <label htmlFor="">姓名</label>
          <input type="text" ref={this.nameInputRef} />
        </div>
        <PasswordInput ref={this.passwordRef} />
        <AgeInputRef ref={this.ageInputRef} />
        <BirthInput />
        <CityInput />
        <HocCountry label="国家" ref={this.countryRef} />
        <div>
          <button onClick={this.submit}>提交</button>
        </div>
      </div>
    );
  }
}

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

  getPassword = () => {
    return this.passwordInputRef.current.value;
  };

  render() {
    return (
      <div>
        <div>
          <label htmlFor="">密码</label>
          <input type="text" ref={this.passwordInputRef} />
        </div>
      </div>
    );
  }
}

function AgeInput(props, ref) {
  return (
    <div>
      <label htmlFor="">年龄</label>
      <input type="text" ref={ref} />
    </div>
  );
}

class BirthInput extends Component {
  constructor(props) {
    super(props);
    this.birthInput = null;
  }

  setTextInputRef = (ele) => {
    console.log("setTextInputRef=======", ele);
    this.birthInput = ele;
  };

  componentDidMount() {
    this.birthInput.value = "123";
    this.birthInput.focus();
  }

  render() {
    return (
      <div>
        <div>
          <label htmlFor="">生日</label>
          <input type="text" ref={this.setTextInputRef} />
          {/* 不建议使用内联 */}
          <input
            type="text"
            ref={(ele) => {
              console.log("setTextInputRef", ele);
              this.birthInput = ele;
            }}
          />
          <button
            onClick={() => {
              let val = this.birthInput.value;
              console.log("birth", val);
            }}
          >
            Click
          </button>
        </div>
      </div>
    );
  }
}

//hook用法
function CityInput(props) {
  const ref = useRef(null);

  return (
    <div>
      <label htmlFor="">区域</label>
      <input type="text" ref={ref} />
      <button
        onClick={() => {
          const value = ref.current.value;
          console.log("city", value); //sy-log
        }}
      >
        click
      </button>
    </div>
  );
}

const hoc = (WrapComponent) =>
  React.forwardRef((props, ref) => {
    return (
      <div>
        <WrapComponent {...props} countryInputRef={ref} />
      </div>
    );
  });

function CountryInput({ label, countryInputRef }) {
  return (
    <div>
      <label htmlFor="">{label}</label>
      <input type="text" ref={countryInputRef} />
    </div>
  );
}

本文是基于React17.0版本

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容