簡體   English   中英

使用 electron ipc 在 React dom 中實時顯示 shell output

[英]display live shell output in react dom using electron ipc

我只能訪問preload.js中的ipcRenderer (我禁用了 nodeIntegration),所以每當我在preload.js中獲得 output 時,如何逐行顯示 output

主程序

function execShellCommands(commands) {
    let shellProcess = spawn("powershell.exe", [commands[0]])

    shellProcess.stdout.on("data", (data) => {
        mainWindow.webContents.send("sendToRenderer/shell-output", data.toString())
    })
    shellProcess.stderr.on("data", (data) => {
        mainWindow.webContents.send("sendToRenderer/shell-output", "stderr: " + data.toString())
    })
    shellProcess.on("exit", () => {
        mainWindow.webContents.send("sendToRenderer/shell-output", "shell-exited")
        commands.shift()
        if (0 < commands.length) {
            execShellCommands(commands)
        }
    })
}
ipcMain.on("sendToElectron/execShellCommands", (event, args) => {
        execShellCommands(args)
})

預加載.js

let API = {
    execShellCommands: (action) => ipcRenderer.send("sendToElectron/execShellCommands", action)
}

contextBridge.exposeInMainWorld("ElectronAPI", API)

ipcRenderer.on("sendToRenderer/shell-output", (event, output) => {
    console.log(output)
})

反應的 App.jsx

ElectronAPI.execShellCommands(["spicetify apply"])

output 在控制台中一一打印,但我如何在p標簽中一一顯示 React DOM (App.jsx) 中的 output?

輸出

首先,您需要在API中公開shell-output偵聽器,以便您的組件可以訪問它:

shellOutput: (callback) => {
  const channel = "sendToRenderer/shell-output";
  const subscription = (_event, output) => callback(output);

  ipcRenderer.on(channel , subscription);

  return () => {
    ipcRenderer.removeListener(channel, subscription);
  };
}

在您的組件上,您現在可以使用 window.ElectronAPI.shellOutput 訪問這個window.ElectronAPI.shellOutput 要記錄輸出,您可以創建一個 state 來存儲它們,並使用useEffect()設置偵聽器:

const [outputs, setOutputs] = useState([]);

useEffect(() => {
  const removeOutputListener = window.ElectronAPI.shellOutput(output => {
    setOutputs(previousOutputs => [
        ...previousOutputs,
        output
    ]);
  });

  return removeOutputListener;
}, []);

return (
  <div>
    {outputs.map((output, i) => (
      <p key={i}>{output}</p>
    ))}
  </div>
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM