我正在使用它来创建产品https://github.com/aldrinc/React360的3D交互式视图。有问题的代码是:
import React, { Component } from "react";
import "./React360.css";
// You can play with this to adjust the sensitivity
// higher values make mouse less sensitive
const pixelsPerDegree = 3;
class React360 extends Component {
static defaultProps = { dir: 'awair-360', numImages: 55 };
state = {
dragging: false,
imageIndex: 0,
dragStartIndex: 0
};
componentDidMount = () => {
document.addEventListener("mousemove", this.handleMouseMove, false);
document.addEventListener("mouseup", this.handleMouseUp, false);
};
componentWillUnmount = () => {
document.removeEventListener("mousemove", this.handleMouseMove, false);
document.removeEventListener("mouseup", this.handleMouseUp, false);
};
handleMouseDown = e => {
e.persist();
this.setState(state => ({
dragging: true,
dragStart: e.screenX,
dragStartIndex: state.imageIndex
}));
};
handleMouseUp = () => {
this.setState({ dragging: false });
};
updateImageIndex = currentPosition => {
let numImages = this.props.numImages;
const pixelsPerImage = pixelsPerDegree * (360 / numImages);
const { dragStart, imageIndex, dragStartIndex } = this.state;
// pixels moved
let dx = (currentPosition - dragStart) / pixelsPerImage;
let index = Math.floor(dx) % numImages;
if (index < 0) {
index = numImages + index - 1;
}
index = (index + dragStartIndex) % numImages;
// console.log(index, dragStartIndex, numImages)
if (index !== imageIndex) {
this.setState({ imageIndex: index });
}
};
handleMouseMove = e => {
if (this.state.dragging) {
this.updateImageIndex(e.screenX);
}
};
preventDragHandler = e => {
e.preventDefault();
};
renderImage = () => {
const { imageIndex } = this.state;
if (isNaN(imageIndex)) {
this.setState({imageIndex: 0})
return
}
return (
<div className="react360">
<img
className="react-360-img"
alt=""
src={require(`./${this.props.dir}/${imageIndex}.jpg`)}
/>
</div>
);
};
render = () => {
return (
<div
className="react-360-img"
onMouseDown={this.handleMouseDown}
onDragStart={this.preventDragHandler}
>
{this.renderImage()}
</div>
);
};
}
export default React360;
我遇到一个问题,即对图像数量(numImages)的变量进行硬编码会导致功能正常,但是当我将图像数量设置为prop let numImages = this.props.numImages;
时,我的图像索引有时会变为NaN。我已经通过将imageIndex状态设置为0(如果是NaN)进行了变通,但我想通过了解使用props和hardcoding设置变量的确切区别来正确解决此问题。