首页 > 解决方案 > 如何在窗口中使用 Google 字体。在 React 中打开

问题描述

我有一个 React 应用程序,并在 onClick 处理程序中打开一个窗口。然后我通过以下方法将文本和样式添加到此窗口:

var myWindow = window.open("", "MsgWindow", "width=200,height=100");
myWindow.document.write("<html><head><style>CUSTOM CSS STYLES HERE</stye></head><p>This is 'MsgWindow'. I am 200px wide and 100px tall!</p></html>")

虽然这适用于传统 CSS,但如果我想添加从 Google Fonts 下载的自定义字体类型,则窗口将无法识别该字体。同样,向头部添加样式表链接似乎不起作用,因为窗口没有对 React 样式表的引用。

在这种情况下,如何使用通常在 window.open 中不可用的 Google?

我知道有一个用于打开窗口的 React 包,但我想避免这种情况。

标签: javascripthtmlcssreactjsgoogle-font-api

解决方案


这可以解决问题

var myWindow = window.open("", "MsgWindow", "width=200,height=100");

myWindow.document.write("<html><head><link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'> <style>body {font-family: 'Roboto', sans-serif;}</stye></head><p>This is 'MsgWindow'. I am 200px wide and 100px tall!</p></html>")

推荐阅读