javascript - React - 按下按钮,继续调用函数

标签 javascript reactjs

我正在尝试实现缩放功能。 onClick 工作正常,但我想在按住缩放按钮时使用它,它会连续缩放。我如何使用 ReactJS 实现它?

Jquery: mousedown effect (while left click is held down) 我将其用作模板,但根据 console.log 未注册 onMousedown

<div className="zoomControl" >
                        <button className="zoomIn" onMouseDown={this.zoomIn}>+</button>
                        <button className="zoomOut" onClick={this.zoomOut}>-</button>
                </div>

zoomIn = () => {
    console.log('test');
    var self = this;
    this.timeout = setInterval(function(){
    // Do something continuously
        this.renderer.zoomIn();
    }, 100);

    return false;

};

zoomMouseUp = () => {
    clearInterval(this.timeout);
    return false;
};

最佳答案

您需要同时使用 mouseUpmouseDown。在 mouseDown 上开始计时,并在超时时重复调用 zoom 函数,并在 mouseUp 上清除时间。

Here a demo with zoomIn and zoomOut to compare and better understand the algorithm .

希望这对您有所帮助!

class Zoom extends React.Component {
   constructor(props) {
     super(props)
     this.state = {
       zoom: 1,
     }
     this.t = undefined
     this.start = 100
     this.repeat = this.repeat.bind(this)
     this.onMouseDown = this.onMouseDown.bind(this)
     this.onMouseUp = this.onMouseUp.bind(this)
     this.zoom = this.zoom.bind(this)
     this.zoomOut = this.zoomOut.bind(this)
   }
   zoom(){
     this.setState({zoom: this.state.zoom + 0.1})
   }
   repeat() {
     this.zoom()
     this.t = setTimeout(this.repeat, this.start)
     this.start = this.start / 2
   }

   onMouseDown() {
     this.repeat()
   }
   onMouseUp() {
     clearTimeout(this.t)
     this.start = 100
   }
   zoomOut(){
     this.setState({
       zoom: 1
     })
   }
  
  render() {
    return <div className="zoomControl" >
      <div className="zoom" style={{transform: 'scale('+ this.state.zoom +')'}}></div>
      <button className="zoomIn" onMouseUp={this.onMouseUp} onMouseDown={this.onMouseDown}>+</button>
      <button className="zoomOut" onClick={this.zoomOut}>-</button>
    </div>
   }
}
  
  ReactDOM.render(<Zoom/>, document.getElementById('app'))
body {
  overflow: hidden
}
.zoom {
  width: 20px;
  height: 20px;
  margin: 0 auto;
  background: red;
}
<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>

关于javascript - React - 按下按钮,继续调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40114942/

相关文章:

javascript - setInterval 仅在对象方法上运行一次

javascript - 如何将js文件中的变量写入html中

javascript - 上一个按钮导致幻灯片消失

javascript - 使用 Jest/Enzyme 检查咏叹调

reactjs - 如何在声明性组件中创建 onChange 事件监听器?

javascript - 特定子项的特定数组 Prop [React]

javascript - 我如何使用 jqueryui 对话框按钮提交表单,

javascript - 我是否错误地使用了文档?

javascript - 使用react redux获取删除请求方法不会删除

reactjs - 将 React ES6 迁移到 TypeScript : import statements don't work