我很难搞清楚如何在没有按钮点击的情况下触发此操作。它在onClick上工作正常,但在其他函数中调用时根本没有。我的代码如下所示:
isCorrect = (newOrder) => {
for (let i = 0 ; i < newOrder.length; i ++) {
if( this.state.displayPlayers[newOrder[i]].rank !== i) {
console.log('loser')
return
}
}
console.log('winner')
this.random();
}
random = () => {
this.setState({
order: [4, 3, 2, 1, 0],
});
};
this.setState适用于按钮单击,但在较大的函数中调用时不起作用。任何帮助表示赞赏。
下面是我的handleMouseMove函数,它触发isCorrect函数。
handleMouseMove = ({ pageY }) => {
const {
isPressed,
topDeltaY,
order,
originalPosOfLastPressed
} = this.state;
if (isPressed) {
const mouseY = pageY - topDeltaY;
const currentRow = clamp(Math.round(mouseY / 100), 0, itemsCount - 1);
let newOrder = order;
if (currentRow !== order.indexOf(originalPosOfLastPressed)) {
newOrder = reinsert(
order,
order.indexOf(originalPosOfLastPressed),
currentRow
);
this.isCorrect(newOrder)
}
//console.log(newOrder);
//console.log(this.state);
this.setState({ mouseY: mouseY, order: newOrder });
}
这是我的整个渲染/返回语句:
render() {
const { mouseY, isPressed, originalPosOfLastPressed, order } = this.state;
return (
<div className="demo8">
<Button onClick = {() => this.random()}> click </Button>
<Button onClick={this.ypcGame}> ypc game</Button>
{this.state.displayPlayers.map((player, i) => {
//console.log(i);
const style =
originalPosOfLastPressed === i && isPressed
? {
scale: spring(1.1, springConfig),
shadow: spring(16, springConfig),
y: mouseY
}
: {
scale: spring(1, springConfig),
shadow: spring(1, springConfig),
y: spring(order.indexOf(i) * 100, springConfig)
};
return (
<Motion style={style} key={i}>
{({ scale, shadow, y }) => (
<div
onMouseDown={this.handleMouseDown.bind(null, i, y)}
onTouchStart={this.handleTouchStart.bind(null, i, y)}
className={
order.indexOf(i) == player.rank
? 'correct demo8-item '
: 'incorrect demo8-item'
}
style={{
boxShadow: `rgba(0, 0, 0, 0.2) 0px ${shadow}px ${2 *
shadow}px 0px`,
transform: `translate3d(0, ${y}px, 0) scale(${scale})`,
WebkitTransform: `translate3d(0, ${y}px, 0) scale(${scale})`,
zIndex: i === originalPosOfLastPressed ? 99 : i
}}>
{order.indexOf(i)}
{order.indexOf(i) == player.rank ? 'correct' : 'incorrect'} :
{order.indexOf(i) == player.rank ? null : (complete = false)}
{player.displayName}
</div>
)}
</Motion>
);
})}
</div>
);
}