Skip to content

ref & forwardRef #3

@CyfforPro

Description

@CyfforPro
import React from "react";

// 通过React.forwardRef,可以将ref从父组件传下去,否则ref的prop是会被React.createElement处理掉的
const Child = React.forwardRef((props, ref) => {
  return <div ref={ref}>{props.initText}</div>;
});

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.fnRef = null;
    this.createdRef = React.createRef(); // { current: null }
    this.childDiv = React.createRef();
  }

  componentDidMount() {
    setTimeout(() => {
      // string ref, 会在this.refs的对应key上挂载ref实例(dom或者class component)
      // 过时的,不推荐使用
      this.refs.div1.innerHTML = "string ref";
      // 回调ref,直接挂到实例属性上了
      this.fnRef.innerHTML = "function ref";
      // createRef的方式,会挂载到.current上,推荐
      this.createdRef.current.innerHTML = "created ref";

      this.childDiv.current.innerHTML = 'forward ref';
    }, 1000);
  }

  render() {
    return (
      <div>
        {/* ref的三种使用方式 */}
        <div ref="div1">test</div>
        <div
          ref={ref => {
            this.fnRef = ref;
          }}
        >
          test
        </div>
        <div ref={this.createdRef}>test</div>
        <Child initText="child" ref={this.childDiv} />
      </div>
    );
  }
}

export default Parent;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions