代码之家  ›  专栏  ›  技术社区  ›  gene b.

在React中使用forwardRef()具体呈现了什么

  •  1
  • gene b.  · 技术社区  · 3 年前

    下面是我从另一个来源获得的片段。我有一个主要的功能部件,叫做 AgreementForm ,需要支持插件提供的打印到PDF功能, React-to-Print .方法是“包装” 协议书 在一个 forwardRef 并将其传递给后面定义的下一个组件,即React to Print组件。这个片段很管用,但我不明白它是干什么的,

    我的问题是,

    • 协议书 自己渲染过吗?

    • 如果不是,谁来定义 PrintComponent 随时渲染, 而不是 协议书 ?

    • 这个表达是什么 {(el) => (componentRef = el)}

       export const AgreementForm = React.forwardRef((props, ref) => {
             // State vars...
             const [myVar, setMyVar] = useState(null);
             // useEffects...
             useEffect(() => { 
             }, [myVar]);
             // Render...
             return (
                <>...</>
             );
      
        // This is print component to wrap the print button and content.
        export default function PrintComponent(props) {
           let componentRef = useRef();
      
           return (
           <>
            <div>
                <ReactToPrint 
                    trigger={() => <Button style={{'margin-bottom':'15px'}}>Print</Button>}
                    content={() => componentRef}
                />
      
              {/* component to be printed */}
              <AgreementForm userInfo={props.userInfo} ref={(el) => (componentRef = el)} />
            </div>
          </>
        );
       }
      
    0 回复  |  直到 3 年前
        1
  •  1
  •   Fyodor Yemelyanenko    3 年前

    首先,提供的代码样本似乎是从React到PDF的两个样本的组合 doc page :从类组件调用和从功能组件调用。请注意,当从类组件调用时, AgreementForm 应该是这样的 <AgreementForm ref={el => (this.componentRef = el)} /> .从函数组件调用时,应该这样使用 <AgreementForm ref={componentRef} /> .

    所提供的示例中的代码将无法正常工作 <AgreementForm userInfo={props.userInfo} ref={(el) => (componentRef = el)} /> 将指定ref( el )到 componentRef 变量下一次渲染时, let componentRef = useRef(); 将ref重新分配给 组件参考 变量所以 ReactToPrint 永远不会得到裁判 协议书 1.总是会有 undefined/null .

    要更正此问题,请使用 <AgreementForm userInfo={props.userInfo} ref={(el) => (componentRef.current = el)} /> .必须将部件的参考号指定给 .current ref变量的属性。

    这条线呢 content={() => componentRef} 也应该改为 content={() => componentRef.current}

    以及问题的答案:

    1. 协议书 PrintComponent 是渲染的。
    2. 打印组件 应该由更高级别的组件渲染,以便打印工作
    3. 如上所述,第1行 {(el) => (componentRef = el)} 这是不正确的。应该是的 {(el) => (componentRef.current = el)} .这一行将指定 协议书 参考 componentRef.current ,哪个leter可以成为消费者 反应打印