React 源码阅读-5

源码

import {REACT_FORWARD_REF_TYPE, REACT_MEMO_TYPE} from 'shared/ReactSymbols';import warningWithoutStack from 'shared/warningWithoutStack';export default function forwardRef<Props, ElementType: React$ElementType>(  render: (props: Props, ref: React$Ref<ElementType>) => React$Node,) {// ... 暂时忽略 也看不太懂//应该这部分代码是为了在DevTools中显示一个自定义名称 不太确定  return {    $$typeof: REACT_FORWARD_REF_TYPE,    render,  };}

React.forwardRef 接受一个渲染函数,该函数接收 propsref 参数并返回一个 React 节点

为了在高阶组件中转发 refs

forwardRef例子

const FancyButton = React.forwardRef((props, ref) => (  <button ref={ref} className="FancyButton">    {props.children}  </button>));// 你可以直接获取 DOM button 的 ref:const ref = React.createRef();<FancyButton ref={ref}>Click me!</FancyButton>;

1.我们通过调用 React.createRef 创建了一个 React ref 并将其赋值给 ref 变量。

2.我们通过指定 refJSX 属性,将其向下传递给<FancyButton ref={ref}>

3.React 传递 reffowardRef 内函数 (props, ref) => ...,作为其第二个参数。

4.我们向下转发该 ref 参数到<button ref={ref}>,将其指定为 JSX 属性。

5.当 ref挂载完成,ref.current 将指向 <button> DOM节点。

用法

  • 写高阶组件时,返回的无状态组件用 forwardRef 包裹,并且可以传递第二个参数 ref
  • 无状态组件中的返回值可将 ref 作为 props 传入。
import React from 'react'// 高阶组件,注意返回值用 `React.forwardRef` 包裹// 里面的无状态组件接收第二个参数:refconst paintRed = Component => React.forwardRef(    // 此例中,ref 为 ForwardRef 中的 textRef    (props, ref) => (        <Component color='red' ref={ref} {...props}></Component>    ))class Text extends React.Component {    // 仅用于检测是否取到 ref    value = 1    render() {        const style = {            color: this.props.color        }        return (            <p style={style}>                我是红色的!            </p>        )    }}const RedText = paintRed(Text)export default class ForwardRef extends React.Component {    textRef = React.createRef()    componentDidMount() {        // value = 1        console.log(this.textRef.current.value)    }    render() {        // 如果没有 forwardRef,那么这个ref只能得到 `RedText`,而不是里面的 `Text`        return (            <RedText ref={this.textRef}></RedText>        )    }}

大部分需要使用 forwardRef 的时候都可以用其他方式解决.

https://juejin.im/post/5ad949...