home wiki.fukuchiharuki.me
Menu

  • 追加された行はこの色です。
  • 削除された行はこの色です。
#author("2018-05-08T10:11:42+00:00","default:haruki","haruki")
&color(red){違うちがう、refの使い方間違えてるかも。};

#author("2018-05-09T01:39:11+00:00","default:haruki","haruki")
* キーワード [#g7102040]
- React
- コンポーネント
- react-new-window

* したいこと [#p7c0026b]

react-new-window で開いた別ウィンドウを印刷させたい、のがきっかけ。

 window.print();

すると、親ウィンドウが印刷されてしまう。

ので、react-new-window がそのコンポーネントで保持する this.window の値を取得したい。react-new-window は window.open() したときの戻り値を this.window に保持している。

* どうやって [#dcf654a4]

ref を使う。

 <NewWindow {...newWindowProps} ref={element => this.printWindow = element ? element.window : null} />
 <NewWindow {...newWindowProps} ref={element => this.newWindow = element} />

目的の window オブジェクトでプリントするには、

 this.newWindow.window.print();

* ちなみに [#yd4b5d7e]

element がないよ、みたいなタイミングがあったので三項演算子した。
%%element がないよ、みたいなタイミングがあったので三項演算子した。%%

なお、this.printWindow とするには関数ではくて React.Component のサブクラスにする必要がある。
%%なお、%%this.newWindow とするには関数ではくて React.Component のサブクラスにする必要がある。

* 参考 [#f88dafc9]
- [[Refs and the DOM - React>https://reactjs.org/docs/refs-and-the-dom.html]]
- [[rmariuzzo/react-new-window: 🔲 Pop new windows in React, using `window.open`.>https://github.com/rmariuzzo/react-new-window]]
- [[Reactのrefを理解する@Typescript - Qiita>https://qiita.com/knknkn1162/items/29d675c8cd26592a95b5]]