簡體   English   中英

使用 Elastic UI 時,未使用 NextJS 定義 Window

[英]Window is not defined with NextJS when using Elastic UI

只是嘗試從Elastic UI庫中添加一個按鈕,但在添加按鈕時未定義 window API 調用和其他一切工作正常,直到我添加按鈕組件或在下面第 3 行添加導入。

在進行服務器端 api 調用時,有沒有辦法使用 Elastic UI 庫?

這是主要代碼:

import React from "react";
import "isomorphic-unfetch";
import { EuiButton } from "@elastic/eui";

export default class HomePage extends React.Component {
  static async getInitialProps() {
    let res = await fetch("https://api.randomuser.me/");
    let randUser = await res.json();
    console.log(randUser);
    return { users: randUser };
  }

  render() {
    return (
      <div>
        <h2>User info:</h2>
        <ul>
          {this.props.users.results.map((user, i) => {
            return <li key={"user-" + i}>{user.gender}</li>;
          })}
        </ul>
        <EuiButton href="http://www.elastic.co">Link to elastic.co</EuiButton>
      </div>
    );
  }
}

不知道這是否是正確的解決方案,但我會探索下一個動態導入。

我設法讓以前的代碼在我身邊工作,但不知道渲染按鈕是否 100% 是你所期望的。

import React from "react";
import dynamic from 'next/dynamic'
import "isomorphic-unfetch";

export default class HomePage extends React.Component {
  static async getInitialProps() {
    let res = await fetch("https://api.randomuser.me/");
    let randUser = await res.json();
    console.log(randUser);
    return { users: randUser };
  }

  render() {
    // dynamic import of the button
    const EuiButton = dynamic(() => import('@elastic/eui/').then(module => module.EuiButton))

    return (
      <div>
        <h2>User info:</h2>
        <ul>
          {this.props.users.results.map((user, i) => {
            return <li key={"user-" + i}>{user.gender}</li>;
          })}
        </ul>
        {/*render it only if we're from client side*/}
        {process.browser ? <EuiButton href="http://www.elastic.co">Link to elastic.co</EuiButton> : null }
      </div>
    );
  }
}

希望這可以讓您了解如何解決您的問題。

暫無
暫無

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

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