与event.which - undefined的reactjs中的问题

时间:2017-07-02 13:31:30

标签: reactjs events

我在画布上有活动onMouseDown -

 <canvas id="myCanvas" width="150" height="150" onMouseMove={this.beginNewPatch.bind(this)}></canvas>

但是当我移动到画布上方时,如果用e.which点击鼠标上的左键,我现在试图获取,但这会打印undefined。有什么提示吗?

beginNewPatch(e){
  console.log(e.which);
  if (e.which === 1) {
    let dot, eventDoc, doc, body, pageX, pageY;
    e = e  || window.event;
  }
}

1 个答案:

答案 0 :(得分:0)

尝试使用event.button(请参阅此处MDN):

class App extends React.Component {
  constructor() {
    super();
    this.beginNewPatch = this.beginNewPatch.bind(this);
  }
  
  componentDidMount() {
    const ctx = this.refs.canvas.getContext('2d');
    ctx.fillRect(0,0, 100, 100);
  }
  
  beginNewPatch(event) {
    console.log(event.button);
  }
  
  render() {
    return (
      <canvas
        ref="canvas"
        width={100}
        height={100}
        onMouseDown={this.beginNewPatch}
      />
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
<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>