此笔显示我的问题:http://codepen.io/PiotrBerebecki/pen/RKxOKb
我可以在单击按钮时更改背景颜色但是我想在单击时按住Shift键时应用不同的颜色。我当前的事件对象似乎无法访问键盘事件。
你知道如何解决它吗?
这是React代码:
class App extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
this.state = {
wasOriginalColorChanged: false,
buttonColor: 'blue'
}
}
handleClick(e) {
let newButtonColor;
if (!this.state.wasOriginalColorChanged) {
if (e.shifKey) {
newButtonColor = 'green';
} else {
newButtonColor = 'tomato';
}
} else {
newButtonColor = 'blue';
}
this.setState({
buttonColor: newButtonColor,
wasOriginalColorChanged: !this.state.wasOriginalColorChanged
});
}
render() {
return (
<div className="button"
onClick={this.handleClick}
style={{backgroundColor: this.state.buttonColor}}>
<p>Click me to change color to tomato</p>
<p>Click me + Shift key to change color to green</p>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
&#13;
.button {
color: white;
text-align: center;
border: solid 5px black;
cursor: pointer;
user-select: none;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;
答案 0 :(得分:6)
你遗漏了&#39; t&#39;在e.shiftKey
中的第二个if语句