【问题标题】:Window is not defined with NextJS when using Elastic UI使用 Elastic UI 时,未使用 NextJS 定义窗口
【发布时间】:2020-04-28 19:54:15
【问题描述】:

只是试图从Elastic UI 库中添加一个按钮,但在添加按钮时只是得到一个未定义窗口。在我添加按钮组件或在下面的第 3 行添加导入之前,API 调用和其他一切工作正常。

在进行服务器端 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>
    );
  }
}

【问题讨论】:

    标签: reactjs next.js elasticui


    【解决方案1】:

    不知道这是否是正确的解决方案,但我会探索下一个动态导入。

    我设法让之前的代码在我身边工作,但不知道渲染按钮是否 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>
        );
      }
    }
    

    希望这可以让您了解如何解决您的问题。

    【讨论】:

      猜你喜欢
      • 2019-10-12
      • 2021-03-30
      • 2019-10-05
      • 2020-06-25
      • 2020-09-18
      • 1970-01-01
      • 2022-12-24
      • 1970-01-01
      • 2021-05-30
      相关资源
      最近更新 更多