我在這里尋找一些指導和建議。我的嘗試和理論將在底部。
我有一個 NextJS 專案,我想從中匯出頂級組件(本質上是入口檔案),以便可以將其用作儀表板中的預覽。
nextjs 專案非常簡單。為了簡單起見,讓我們假設它渲染的只是一個彩色的<h1>Hello world</h1>. 然后在我的儀表板中,我想渲染一個嵌入了我的 NextJS 組件的手機,然后從儀表板更改文本的顏色,作為預覽它的外觀的一種方式。我希望這是有道理的。
我不知道如何從 NextJS 匯出這個組件并將其匯入我的儀表板。儀表板在 Ruby on Rails 中呈現。只需從 git 匯入 repo 并直接從 node_modules 訪問檔案就足夠簡單了,但我正在尋找一種不需要在我們的 Rails 專案上安裝 npm 的解決方案。
我想過的路徑:
1 - 在 Rails 上安裝 npm 并從 NextJS repo 匯入源代碼并訪問檔案并使用 react 渲染(簡單,但我們正在尋找非 npm 解決方案)
2 - 將組件與 webpack 捆綁在一起并將其直接加載到 rails 中(這是否有效?) - 我匯出了 js,它所做的只是凍結所有內容:P 目前仍在嘗試這條路徑
3 - 使用 iframe 并僅訪問頁面(然后我無法將任何回呼傳遞到 iframe 以直接從儀表板更改顏色)
4 - 我無法將此組件與 NextJS 分開以用作兩個存盤庫中的庫。我們正在匯出的組件是“整個”NextJS 應用程式 jsx,在不同的 repo 中分離是沒有意義的
有人對我如何實作這一目標有建議嗎?
uj5u.com熱心網友回復:
我認為您可以將 iframe 與 nextjs 應用程式網址一起使用。然后如果你想改變顏色,只需在 iframe 的查詢引數中添加顏色并在 nextjs 應用程式上處理它。
簡單的例子
Rails 視圖 (erb)
<iframe src="#{@nextjs_url}?color=#{@color}" />
NextJS
# do something to get the query param of the page and and set to prop of the component
const YourComponent = ({color}) => {
return <h1 style={{color}}>Lorem</h1>;
}
uj5u.com熱心網友回復:
在嘗試 Hoang 的解決方案時,我決定深入研究如何與 iframe 進行通信,并且該解決方案實際上感覺非常好。
您可以在任一側設定偵聽器并在專案之間發布訊息。
所以在我的儀表板中:
function handleEvent(e) {
const data = JSON.parse(e.data)
if (data.type === "card_click") {
//if type is what we want from this event, handle it
}
}
// Setup a listener with a handler
// This will run every time a message is posted from my app
window.addEventListener("message", handleEvent, false)
const postMessage = (color) => {
const event = JSON.stringify({
type: "color_update",
color,
})
// Find the iframe and post a message to it
// This will be picked up by the listener on the other side
document.getElementById("my-iframe-id").contentWindow.postMessage(event, "*")
}
在我的應用程式上:
function handleEvent(e) {
const data = JSON.parse(e.data)
if (data.type === "color_update") {
// Do whatever is necessary with the data
}
}
// Setup listener
// This will fire with every message posted from my dashboard
window.addEventListener("message", handleEvent, false)
const handleCardClick = (cardIndex) => {
const event = JSON.stringify({
type: "card_click",
cardIndex,
})
// post message to parent, that will be picked up by listener
// on the other side
window.parent.postMessage(event, "*")
}
使用此解決方案與 iframe 進行通信感覺非常簡單。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/488872.html
下一篇:在React中洗掉行內塊錯誤腳本
