React中使用ref获取DOM和组件,函数组件forwardRef的使用,受控组件和非受控组件

65 阅读1分钟

如何使用ref

import React, { PureComponent, createRef } from "react";

export class App extends PureComponent {
  constructor() {
    super();
    this.state = {
      msg: "zm6",
    };
    this.zmRef = createRef();
    this.zmEle = createRef();
  }
  getDOM() {
    // 1.在React元素上绑定一个ref字符串
    console.log("this.refs.zm=> ", this.refs.zm);

    // 2.提前创建好ref对象,createRef(),将创建出来的对象绑定到元素ref属性上,
    //<h2 ref={this.zmRef}>hello,zm</h2>   通过current获取dom
    console.log("this.zmRef.current=> ", this.zmRef.current);

    // 3.传入一个回调函数,在对应元素被渲染之后,回调函数被执行,并且将元素传入
    console.log("this.zmEle=> ", this.zmEle);
  }
  render() {
    return (
      <div>
        <h2 ref="zm">zm</h2>
        <h2 ref={this.zmRef}>hello,zm</h2>
        <h2 ref={(element) => (this.zmEle = element)}>hello,ww</h2>
        <button onClick={(e) => this.getDOM()}>getDOM</button>
      </div>
    );
  }
}
export default App;

image.png

ref转发

image.png

ref的类型

image.png

获取类组件和函数组件实例

import React, { PureComponent, createRef, forwardRef } from "react";

class ClassComponent extends PureComponent {
  print() {
    console.log("print被调用");
  }
  render() {
    return <h1>ClassComponent</h1>;
  }
}

const FnComponent = forwardRef(function (props, ref) {
  return (
    <div>
      <h1 ref={ref}>hello fn wzm</h1>
      <p>666</p>
    </div>
  );
});

export class App extends PureComponent {
  constructor() {
    super();

    // 类组件实例
    this.classzmRef = createRef();
    // 函数组件实例
    this.fnzmRef = createRef();
  }
  getComponent() {
    // 获取类组件实例 *
    console.log("this.classzmRef=> ", this.classzmRef.current);
    this.classzmRef.current.print(); //调用子组件方法

    // 获取函数组件实例中某一个元素dom
    console.log("this.fnzmRef.current=> ", this.fnzmRef.current);
  }
  render() {
    return (
      <div>
        <div>
          {/* 获取类组件实例 */}
          <ClassComponent ref={this.classzmRef} />
          <button onClick={(e) => this.getComponent()}>getComponent</button>

          {/* 获取函数组件实例 */}
          <FnComponent ref={this.fnzmRef} />
        </div>
      </div>
    );
  }
}
export default App;

image.png

受控组件和非受控组件

认识受控组件:

image.png

import React, { PureComponent } from "react";

export class App extends PureComponent {
  constructor() {
    super();
    this.state = {
      name: "default_name",
    };
  }
  inputChange(event) {
    console.log("event.target.value=> ", event.target.value);
    this.setState({
      name: event.target.value,
    });
  }
  render() {
    const { name } = this.state;
    return (
      <div>
        {/* 受控组件  value受控于state ,如果没有实现onChange事件,输入框不能输入东西 */}
        <input type="text" value={name} onChange={(e) => this.inputChange(e)} />

        {/* 非受控组件 */}
        <input type="text" />
        <h2>App-name-{name}</h2>
      </div>
    );
  }
}
export default App;