【问题标题】:UseRef to select the parent component of the actual oneUseRef 选择实际的父组件
【发布时间】:2021-07-22 11:35:06
【问题描述】:

我正在使用 useRef 选择一个组件并打印它。

这是组件:

import React, { useRef } from 'react';
import { useReactToPrint } from 'react-to-print';

const Details = ({ view }) => {
  const componentRef = useRef();
  const handlePrint = useReactToPrint({
    content: () => componentRef.current
  });

  return (
    <div className="order-details-section" ref={componentRef}>
      <div className="return-an-issue-header">
        <div className="return-an-issue-title"></div>
        {view && (
          <div className="print-items-container">
            <p onClick={handlePrint}>click to print</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default Details;

它工作正常,但仅适用于作为整个页面一部分的当前组件。我想打印父组件,或者通过 className 传递它。

有可能做这样的事情吗?在useRef中获取父组件还是按类选择?

【问题讨论】:

  • 如果必须打印父组件,为什么不使用父组件中的钩子?
  • @ShubhamKhatri 因为打印按钮必须位于子组件内。样式问题
  • 添加了关于方法的答案

标签: javascript reactjs react-hooks ref use-ref


【解决方案1】:

您可以将 ref 传递给子组件,就像您通常将 props 传递给子组件一样。

注意: Ref 不会触发重新渲染,所以当输入值发生变化时,需要点击按钮获取新值。

这只是一个演示将 ref 传递给子组件的代码示例。

Codesandbox

import { useRef, useState } from "react";
export default function App() {
  const inputRef = useRef();
  return (
    <div className="App">
      <input ref={inputRef} />
      <ChildComponent parentRef={inputRef} />
    </div>
  );
}

const ChildComponent = ({ parentRef }) => {
  console.log("parentRef", parentRef);

  const [value, setValue] = useState("");
  const getValue = () => {
    setValue(parentRef.current.value);
  };
  return (
    <>
      <h1>Child Component</h1>
      {value}
      <button onClick={getValue}>Get Value</button>
    </>
  );
};

【讨论】:

    【解决方案2】:

    如果您想访问父组件的 ref 并打印它,您可以将 useReactToPrint 移动到父组件并将 handlePrint 函数作为道具传递给子组件

    const Details = ({ view, handlePrint}) => {
    
      return (
        <div className="order-details-section">
          <div className="return-an-issue-header">
            <div className="return-an-issue-title"></div>
            {view && (
              <div className="print-items-container">
                <p onClick={handlePrint}>click to print</p>
              </div>
            )}
          </div>
        </div>
      );
    };
    
    export default Details;
    

    const Parent = () => {
    
      const componentRef = useRef();
      const handlePrint = useReactToPrint({
          content: () => componentRef.current
      });
      return (
          <div ref ={componentRef}> 
             <div>Some other content</div>
             <Details view={...} handlePrint={handlePrint}/>
         </div>
      )
    }
    

    【讨论】:

    • 它表示 Child 中的 handlePrint 未定义。不应该作为道具发送吗?
    • @JeanPierre,是的,它应该作为道具发送,编辑时错过了
    猜你喜欢
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多