美文网首页
react中获取dom以及使用ref

react中获取dom以及使用ref

作者: milletmi | 来源:发表于2019-09-27 18:21 被阅读0次

    一、react中获取dom有以下提供三种方法:

    1. js 常规dom操作方式,通过id获取dom
    const dom = document.getElementById('aaa');
    const height = dom.offsetHeight;
    

    2.react原生函数findDOMNode获取dom

    const dom = document.getElementById('aaa');
     const height =  ReactDOM.findDOMNode(submitObj).offsetHeight
    

    3.通过ref来定位一个组件,切记ref要全局唯一(类似id)

    <div ref="module"></div>
    const height = this.module.offsetHeight ;
    

    ref Callback 属性
    React支持一种非常特殊的属性,你可以附加到任何的组件上。 ref 属性可以是一个回调函数,这个回调函数会在组件被挂载后立即执行。被引用的组件会被作为参数传递,回调函数可以用立即使用这个组件,或者保存引用以后使用(或者二者皆是)。

    <div ref={(c) => this.module = c}></div>
    const height1 = this.module.offsetHeight ;
    

    二、转发 Refs

    Ref 转发是一种选择性加入的功能,可让某些组件接收他们收到的 ref,并将其向下传递(换句话说,“转发”)给孩子。
    使用 React.forwardRef 来获取传递给它的 ref , 然后将其转发给它渲染的的 DOM button:

    const FancyButton = React.forwardRef((props, ref) => (
      <button ref={ref} className="FancyButton">
        {props.children}
      </button>
    ));
    
    // You can now get a ref directly to the DOM button:
    const ref = React.createRef();
    <FancyButton ref={ref}>Click me!</FancyButton>;
    

    通过这种方式,使用 FancyButton 的组件可以获得底层 button DOM 节点的引用并在必要时访问它 - 就像他们直接使用 DOM button 一样。

    以下是对上述示例中发生情况逐步的说明:

    1. 我们通过调用 React.createRef 创建一个 React ref 并将其分配给 ref 变量。
    2. 通过将 ref 变量传递给指定ref为 JSX 属性的 <FancyButton ref={ref}>
    3. Reac t将ref传递给 forwardRef 中的 (props, ref) => ... 函数作为第二个参数。
    4. 我们将这个ref参数转发到指定ref为 JSX 属性的 <button ref = {ref}>
    5. 当附加 ref 时,ref.current 将指向 <button> DOM节点。
      注意 第二个 ref 参数仅在使用 React.forwardRef 调用定义组件时才存在。常规函数或类组件不接收 ref 参数,而且 props 也不提供 ref 。 Ref 转发不限于 DOM 组件。您也可以将 refs 转发给类组件实例。

    相关文章

      网友评论

          本文标题:react中获取dom以及使用ref

          本文链接:https://www.haomeiwen.com/subject/ssgyjctx.html