我正在尝试复制这个 https://codepen.io/swizec/pen/bgvEvp
我已经用 npm 安装了 d3-timer 包 https://www.npmjs.com/package/d3-timer
它肯定存在,因为我已经通读了这些文件。
我困惑的是如何将计时器导入我的代码。在 codepen 上的代码中,它只使用 d3.timer 但没有显示上面的导入。所以我尝试导入 d3 但在 d3-timer 包中找不到它。我尝试了定时器,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”)。
最佳答案
尝试
从 'd3-timer' 导入 { timer }
然后使用 timer()
关于javascript - 如何找出可以从 npm 包中导出的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61735087/