问题描述
我需要将 npm 上可用的 Slot Machine 组件作为“react-slot-machine-gen”导入并使用到我的 React 应用程序中。我正在尝试在安装了 create-react-app 的 React 应用程序中使用它。使用 Yarn 将其添加到现有项目中,如 npm 中所述。 我的 App.js 导入 Demo 组件,该组件返回一个 SlotMachine 组件和一个运行它的按钮。 在 Demo.js 组件中,我添加了更多卷轴,以便我有 3 个旋转卷轴。我将 imageSrc 属性路径添加到 reel-strip.png 图像(每个都是真实的)。 所以,最后我的 App.js 是:
import './App.css';
import React,{ Fragment,Component } from 'react';
import Demo from './components/Demo';
class App extends Component {
render() {
return (
<Fragment>
Hello App
<Demo />
</Fragment>
);
}
}
export default App;
我的 Demo.js 是:
import React,{ Component } from 'react';
import SlotMachine from 'react-slot-machine-gen'; // or '../dist/react-slot-machine-gen';
const reels = [
{
imageSrc: 'srcimages\reel-strip1.png',symbols: [
{
title: 'cherry',position: 100,weight: 2,},{
title: 'plum',position: 300,weight: 6,{
title: 'orange',position: 500,weight: 5,{
title: 'bell',position: 700,weight: 1,{
title: 'cherry',position: 900,weight: 3,position: 1100,],{
imageSrc: 'srcimages\reel-strip2.png',symbols: [
{
title: 'orange',{
imageSrc: 'srcimages\reel-strip3.png',weight: 4,];
class Demo extends Component {
constructor() {
super();
this.state = {
play: false,};
}
playEvent() {
this.setState({
play: !this.state.play,});
}
render() {
return (
<React.Fragment>
<SlotMachine reels={reels} play={this.state.play} />
<button id='play-button' onClick={() => this.playEvent()}>
Play
</button>
</React.Fragment>
);
}
}
export default Demo;
当我使用 npm start 运行我的项目时,我收到编译错误(参见图 2)。
解决方法
看到错误是因为react版本不匹配。 react-slot-machine-gen
使用 react@^16.13.1
。
由于您使用了 create-react-app 样板代码,当前版本使用第 17 版 react。 react-slot-machine-gen
使用第 16 版。
将您的 react 和 react-dom 版本降级到 16.14.0
并进行验证。
由于您将使用 16.14.0,因此需要在必要时添加 import React from "react"
。
代码沙盒链接 https://codesandbox.io/embed/exciting-feather-dihcn?file=/src/Slot.js