使用反应和样式组件打印时如何隐藏按钮?

sar*_*tha 5 typescript reactjs

我想在单击页面中的打印按钮时隐藏打印按钮。打印开始后基本上隐藏网页上的打印按钮。

下面是我的代码,

const printItems = () => {
    window.print();
}

function ItemsTable() {
    return(
        <>
            <TableCell>
                <span>first</span>
            </TableCell>
            <PrintCell>
                <CircleIconButton
                    name="print"
                    onClick={printItems}
                >
            </PrintCell>
        </>
    ); 
}

const TableCell = styled.div`
    display: flex;
    flex-direction: row;
`;

const PrintCell = styled(TableCell)`
    width: 100px;
    justify-content: flex-end;
`;

const CircleIconButton = styled(IconButton)`
    border-radius: 15px;
    background: none;
    width: 32px;
    height: 32px;
`;
Run Code Online (Sandbox Code Playgroud)

现在我想在用户单击 CircleIconButton 时隐藏 PrintCell。我怎样才能用CSS和媒体打印来做到这一点。

有人可以帮我吗?谢谢。

Den*_*ash 5

您有多种解决方案:

条件渲染

function ItemsTable() {
  const [isPrinting, setIsPrinting] = useState(false);

  const printItems = () => {
    setIsPrinting(true);
    window.print();
  };

  return (
    <>
      {!isPrinting && (
        <PrintCell>
          <CircleIconButton name="print" onClick={printItems} />
        </PrintCell>
      )}
    </>
  );
Run Code Online (Sandbox Code Playgroud)

使用 CSS 变量

function ItemsTable() {
  const [isPrinting, setIsPrinting] = useState(false);

  const printItems = () => {
    setIsPrinting(true);
    window.print();
  };

  return (
    <>
      <PrintCell isVisible={isPrinting}>
        <CircleIconButton name="print" onClick={printItems} />
      </PrintCell>
    </>
  );
}

// Or any other css prop like `visible`
const PrintCell = styled(TableCell)`
    display: ${props => props.isVisible ? 'block' : 'none'}
`;
Run Code Online (Sandbox Code Playgroud)

使用参考

function ItemsTable() {
  const printRef = useRef();

  const printItems = () => {
    printRef.current.style.display = 'none';
    window.print();
  };

  return (
    <>
      <PrintCell ref={printRef}>
        <CircleIconButton name="print" onClick={printItems} />
      </PrintCell>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

使用媒体查询

const Container = styled.div`
  @media print {
    ${PrintCell} {
      display: none;
    }
  }
`;

const PrintCell = styled(TableCell)`
    width: 100px;
    justify-content: flex-end;
`;

<Container>
  <PrintCell>
    <CircleIconButton name="print" onClick={printItems} />
  </PrintCell>
</Container>
Run Code Online (Sandbox Code Playgroud)

没有“推荐的方式”,选择适合自己的方式,取决于具体情况。