之前使用react.forwardref始终无法应用于react高阶组件中,最近终于捣鼓出来了,于是记录下来。关键点就是react.forwardref的api中ref必须指向dom元素而不是react组件。

react.forwardref使用示例

下面就是应用到react组件的错误示例:

const a=react.forwardref((props,ref)=><b {...props} ref={ref}/>)

这就是我之前经常犯的错误, 这里的ref是无法生效的。

前面提到ref必须指向dom元素,那么正确方法就应用而生:

const  a=react.forwardref((props,ref)=>(
<div ref={ref}>
<b {...props} />
</div>
))

作用与注意点

  1. 父组件创建一个ref对象,绑定给子组件中的dom元素或class组件
  2. 函数组件是没有实例的
  3. 高阶组件需做特殊处理

父组件获取子组件中dom元素实例

import react, { useref } from 'react';
import content from './content';

const home = () => {
  // 创建一个ref对象
  const connectref = useref(null);

  const handlefoucus = () => {
    const _ref = connectref.current;
    _ref.focus();
  };

  return (
    <div>
        <button onclick={() => handlefoucus()}>
          使用子组件中dom元素的方法
        </button>

        <content ref={connectref} />
    </div>
  );
};

export default home;
import react, { forwardref } from 'react';

/**
 * forwardref包裹后,ref会作为第二个参数,接收传进来的ref属性
 * e.g.
 * <content count={count} user={user} ref={connectref}>
 *
 * @param props - {count, user}
 * @param ref   - connectref
 * */
const content = (props, ref) => {
  return (
    <div>
   	  {/* 把ref绑定给传进来的ref ≈ ref={connectref} */}
      <input type="password" ref={ref} />
    </div>
  )
};

export default forwardref(content);

父组件获取子组件中class组件实例

import react, { useref } from 'react';
import content from './content';

const home = () => {
  // 创建一个ref对象
  const connectref = useref(null);

  const handleadd = () => {
    const _ref = connectref.current;

    const { count } = _ref.state;
    _ref.setstate({
      count: count + 1
    })
  };

  return (
    <div>
        <button onclick={() => handleadd()}>
          使用子组件中class组件的属性和方法
        </button>

        <content ref={connectref} />
    </div>
  );
};

export default home;
import react, { forwardref } from 'react';
import header from './header';
import footer from './footer';

/**
 * forwardref包裹后,ref会作为第二个参数,接收传进来的ref属性
 * e.g.
 * <content count={count} user={user} ref={connectref}>
 *
 * @param props - {count, user}
 * @param ref   - connectref
 * */
const content = (props, ref) => {
  return (
    <div>
      {/* 把ref绑定给传进来的ref ≈ ref={connectref} */}
      <header ref={ref} />  {/* class组件 */}
		
      {/* <footer ref={ref} /> 函数组件是没有实例的,所以connectref.current: null */}
    </div>
  )
};

export default forwardref(content)
import react from 'react';

export default class header extends react.component {
  state = {
    count: 0
  };

  render() {
    return (
      <div>
        {this.state.count}
      </div>
    )
  }
};

高阶组件中的特殊情况

会把所有接收到的props,传递给被包装的组件(透传)
ref 和 key 类似,不是一个prop,所以不会透传,ref会绑定到外层的包装容器上

/*
  处理ref
  e.g. hoc1(hoc2(content))

  <content ref={myref} /> 给content绑定的ref会绑定到hoc1上,且不会继续向下传递

  第一种方法 react.forwardref ===============

      在 hoc1外面 用react.forwardref()对ref做处理,用props来传递ref
      0. 在高阶组件外面包裹forwardref,拦截获取ref,增加一个props(xxx={ref}),真实组件通过props.xxx获取
      1. 使用时传 ref={xxxx}  // 和第二种方法不同的地方
      2. 用forwardref的第二个参数获取 ref
      3. 增加一个新的props,用来向下转发ref  e.g. forwardedref={ref}
      4. 真实组件中绑定 ref={props.forwardedref}

      const home = (props) => {
        const connectref = useref(null);

        return (
          <div>
            <content ref={connectref} />
          </div>
        );
      };

      // 被包装组件
      const content = (props) => {
        return (
          <div>
            <input type="password" ref={props.forwardedref} />
          </div>
        );
      };


      // forwardref的第二个入参可以接收ref,在hoc外层对ref做处理
      export default react.forwardref((props, ref) => {
        const wrapper = react.memo(content);  // hoc

        // forwardref包裹的是wrapper
        // 需要在wrapper中把ref向下传递给真实组件
        // wrapper中增加一个props属性,把ref对象作为props传给子组件
        return <wrapper {...props} forwardedref={ref} />;
      });

  第二种方法 ==========

  0. 使用时就用一个props来保存ref
  1. 使用时传 xxx={ref}  // 和第一种方法的不同点
  2. 真实组件中绑定 ref={props.xxx}

  const home = (props) => {
    const connectref = useref(null);

    return (
      <div>
        <content forwardedref={connectref} />
      </div>
    );
  };

  // 定义高阶组件
  export const hoc = (wrappedcomponent) => {
    class wrapper extends react.component {
      render() {
        return <wrappedcomponent {...props} />
      }
    }
  }

  // 被包装的组件
  const content = (props) => {
    return (
      <div>
        <input type="password" ref={props.forwardedref} />
      </div>
    );
  };

  // 包装过程
  export default hoc(content);

* */

以上就是react forwardref的使用方法及注意点的详细内容,更多关于react forwardref使用的资料请关注www.887551.com其它相关文章!