如果你按下空格键,我会出现一个加号。但现在它出现了一次。你能帮我让它在每次按空格键时出现吗?这是我的代码笔。
import './style.scss';
let counter = 0;
document.addEventListener('keydown', ({ keyCode }) => {
const increment = document.getElementsByClassName('increment')[0];
if (keyCode === 32) {
counter++;
document.getElementsByClassName('counter')[0].innerText = counter;
increment.classList.remove('hidden');
increment.classList.add('move-increment');
}
});
Run Code Online (Sandbox Code Playgroud)
.container {
/* ... */
.counter {
background-color: gray;
color: white;
border-radius: 10px;
padding: 10px;
}
.move-increment {
margin-top: -20px;
opacity: 0;
}
.hidden {
visibility: hidden;
}
.increment {
position: absolute;
margin-left: -33px;
z-index: 1;
transition: margin-top 1s cubic-bezier(0, 0.5, 0.5, 1),
opacity 1s ease-in-out;
}
}
Run Code Online (Sandbox Code Playgroud) 我最近阅读了 react.js文档,发现根据之前的状态值设置状态不一致。这是那块代码:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这种() => this.setState({ count: this.state.count + 1 })设置方式state是错误的,您应该为此目的使用回调。所以我提出了PR,其中我添加了对先前状态的回调函数的使用,但它已被弃用,因为
当您不确定捕获的状态值是什么时,回调版本很有用。
我真的不喜欢当你不是解释的某个部分时,有人可以解释为什么这种() => this.setState({ count: this.state.count + 1 })设置状态的方式是正确的。
提前致谢。