每次我单击按钮时,参数始终是{i}的最后一个值(在这种情况下为0),并且我需要具有普通值才能传递给Redux操作。
当我在DIV内部工作时打印。
class MYCLASS extends React.Component {
constructor(props){
super(props);
}
render() {
var level = [];
for (var i = 10; i > 0; i--) {
level.push(
<div>
<div>{i}</div>
<button className='up' onClick={()=>this.props.callUp({i})}>HEREEE!!</button>
<button className='down' onClick={()=>this.props.callDown({i})}>HEREEE!!</button>
</div>
);
}
return level
}
}
const mapDispatchToProps = (dispatch) => ({
callUp: (i) => dispatch(callUp(i)),
callDown: (i) => dispatch(callDown(i)),
})
答案 0 :(得分:2)
遍历循环时,可以将i
的值存储到变量中。每次迭代循环时,都会创建该变量的新实例。然后,您可以将该变量传递到onClick
处理程序中。它的当前值将被使用并存储在阵列的内存中。
如果您不这样做,它将仅使用i
请参阅codeandbox以供参考:https://codesandbox.io/s/fancy-waterfall-kw0kb
import React from "react";
class Test extends React.Component {
renderButtons = () => {
var level = [];
for (var i = 10; i > 0; i--) {
const currentLevel = i;
level.push(
<div>
<div>{currentLevel}</div>
<button className="up" onClick={() => this.props.callUp(currentLevel) }>
HEREEE!!
</button>
<button className="down" onClick={() => this.props.callDown(currentLevel) }>
HEREEE!!
</button>
</div>
);
}
return level;
};
render() {
return <div>{this.renderButtons()}</div>;
}
}
export default Test;
const mapDispatchToProps = (dispatch) => ({
callUp: (i) => dispatch(callUp(i)),
callDown: (i) => dispatch(callDown(i)),
})