【问题标题】:How to find out what can be exported from npm package如何找出可以从 npm 包中导出的内容
【发布时间】:2020-05-11 16:57:03
【问题描述】:

我正在尝试复制这个https://codepen.io/swizec/pen/bgvEvp

我已经用 npm https://www.npmjs.com/package/d3-timer 安装了 d3-timer 包

肯定存在,因为我已经通读了文件。

我很困惑的是如何将计时器导入我的代码中。在 codepen 上的代码中,它只使用 d3.timer 但没有显示上面的导入。所以我尝试导入 d3 但在 d3-timer 包中找不到它。我试过定时器,定时器,D3,d3。

所以我的问题是 - 我如何着手调查包以确定导出的名称是什么?

或者如果这太复杂了 - 在这种特殊情况下,我应该导入什么来获得 d3.timer 的功能?

非常感谢!

来自代码笔的代码:

const Component = React.Component;

const Ball = ({ x, y }) => (
  <circle cx={x} cy={y} r={5} />
);

const MAX_H = 750;

class App extends Component {
  constructor() {
    super();

    this.state = {
      y: 5,
      vy: 0
    }
  }

  componentDidMount() {
    this.timer = d3.timer(() => this.gameLoop());
    this.gameLoop();
  }

  componentWillUnmount() {
    this.timer.stop();
  }

  gameLoop() {
    let { y, vy } = this.state;

    if (y > MAX_H) {
      vy = -vy*.87;
    }

    this.setState({
      y: y+vy,
      vy: vy+0.3
    })

  }

  render() {
    return (
      <svg width="100%" height={MAX_H}>
        <Ball x={50} y={this.state.y} />
      </svg>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

我的代码

import React from 'react';
import d3 from 'd3-timer'

const Component = React.Component;


const Ball = ({ x, y }) => (
    <circle cx={x} cy={y} r={5} />
);

const MAX_H = 750;

export default class App extends Component {
  constructor() {
    super();

    this.state = {
      y: 5,
      vy: 0
    }
  }

  componentDidMount() {
    this.timer = d3.timer(() => this.gameLoop());
    this.gameLoop();
  }

  componentWillUnmount() {
    this.timer.stop();
  }

  gameLoop() {
    let { y, vy } = this.state;

    if (y > MAX_H) {
      vy = -vy*.87;
    }

    this.setState({
      y: y+vy,
      vy: vy+0.3
    })

  }

  render() {
    return (
        <svg width="100%" height={MAX_H}>
          <Ball x={50} y={this.state.y} />
        </svg>
    )
  }
}

错误信息:

尝试导入错误:“d3-timer”不包含默认导出(导入为“d3”)。

【问题讨论】:

    标签: javascript reactjs d3.js npm timer


    【解决方案1】:

    试试

    import { timer } from 'd3-timer' 然后使用timer()

    【讨论】:

    • 没有 d3 模块,只有 d3-timer 包含 d3.timer 的等价物,但不知道如何导入它
    • 编辑了我的答案。
    • 谢谢!这是我缺少的大括号。看来我需要了解命名导出和默认导出之间的区别
    • 所以实际获取导出内容列表太复杂了?
    猜你喜欢
    • 2020-09-02
    • 2020-03-20
    • 2019-09-09
    • 2017-04-12
    • 2019-12-22
    • 2023-01-03
    • 2017-03-15
    • 1970-01-01
    • 2022-06-22
    相关资源
    最近更新 更多