プロジェクトの印刷に対する反応の追加


このブログ記事では、すでに私の最初のプロジェクトを作成します.



一歩一歩

依存関係のインストール
# using yarn
yarn add react-to-print

# using npm
npm i react-to-print

2 -新機能の流れ

インポートのコンセプトはリフティングステートアップです:特定の機能を1つ以上の機能/コンポーネントを追加し、それらを管理するためにそれらを管理するときに、ルートコンポーネントがすべての子コンポーネントのマネージになるように、状態を上げるという概念を使用します.

より多くを見てください:https://reactjs.org/docs/lifting-state-up.html#gatsby-focus-wrapper

3 -フォルダ構造
最良の理解と可視化


4 - ActionButtonを追加する
まず、使用するすべての依存関係をインポートし、使用するコンポーネントの種類を渡します.
import React from "react";
import Button from "@material-ui/core/Button";
import ReactToPrint from "react-to-print";

type ActionButtonProps = {
  componentToPrint: React.MutableRefObject<null>;
};
また、ActionButton関数を作成し、ComponentToPrint関数を同じにし、「戻る」ボタンを押します.
return (
    <>
      <ReactToPrint
        trigger={() => (
          <Button id={"print"} variant="contained" color="primary">
            {" "}
            {"Print"}{" "}
          </Button>
        )}
        content={() => componentToPrint.current}
      />
    </>
  );
ボタンをReactToPrintでラップし、コンポーネントを返し、OnClickをオンにします.
どのように、我々は.currentと関連した構成要素を通してmutableオブジェクトを返すためにuserefフックを使用します.

5 -コンポーネントをtodolistコンポーネントに渡しました
リストの「to」コンポーネントを「div」でラップします.
return (
    <div ref={(el) => (componentToPrint.current = el)}>
      {list.map((item, index) => (
        <div key={item.id}>
          <TextField
            value={item.value}
            onChange={(e) => handleChange(e.currentTarget.value, item.id)}
          />
          <IconButton onClick={() => handleAdd(index)}>
            <AddIcon />
          </IconButton>

          {list.length > 1 && (
            <IconButton onClick={() => handleDelete(item.id)}>
              <DeleteIcon />
            </IconButton>
          )}
        </div>
      ))}
    </div>
  );

6 - ComponentToPrintをコンポーネントルート( app . tsx )に渡します.
最後の手順では、子コンポーネントを管理する親コンポーネントにComponentToPrintを渡します.
アプリケーション関数内でComponentToPrint関数を渡し、ButtonPrintの一部であるすべてのコンポーネントの関係を終了するには、userEFフックを使用します.
const App = () => {
  const componentToPrint = useRef(null);

  return (
    <div className="container">
      <TodoList componentToPrint={componentToPrint} />
      <ActionButton componentToPrint={componentToPrint} />
    </div>
  );
};

結果

🔗 ギタブ

biantris / todolist
📝TODOリスト+反応フック+材料のUI +印刷に反応

藤堂一覧
さて、提示されるプロジェクトは非常に簡単ですが、反応についての基本的な知識を統合するのに役立っています、私はコードがより読みやすくて、単純になるので、私はTypesScriptを使うことを選びました、しかし、あなたが好むならば、あなたは通常のJavaScriptを使うことができます.
プロジェクトが使用されます.
  • タイプスクリプト
  • 反応フック
  • の材料UI
  • ステップバイステップバイステップ
    🔗
    新しい妙技の印刷ボタンを追加する記事
    🔗
    新機能react-to-print

    始める
    1 -クローンリポジトリ.
    2 -依存関係をインストールします.

    ////
    糸のインストール
    //
    糸開始
    デモ
    🔗 https://todolist-one-psi.vercel.app
    コデワンボックス
    🔗 https://codesandbox.io/s/react-to-print-f5tje?file=/src/App.tsx
    View on GitHub
    🔗 Codesandbox : https://codesandbox.io/s/react-to-print-f5tje?file=/src/App.tsx