Hammerjs和React:检测捏事件的结束

时间:2018-11-08 12:03:18

标签: javascript reactjs hammer.js

我需要能够检测到捏事件的“结束”。使用Hammerjs似乎应该很容易,但是相反,我遇到了多个挤压事件。此外,似乎在捏合事件之一中应该设置event.isFinal标志,但这没有发生。

基本的反应应用程序结构如下

class App extends React.Component {

    state = {   urls: [],
                header:[""] };

    render() {
        return (<div>
                    {this.state.header.map(item => <span>{item}<br/></span>)}
                    <div className="grid" ref={elem => this.gridElement = elem}>
                        {this.state.urls.map(entry => {
                            const fullSizeUrl = imageURL + entry.slice(0,-1-sizeEnding.length) + '.jpg'
                            return (<div className="cell" key={fullSizeUrl}>
                                        <a href={fullSizeUrl}><img src={imageURL + entry} className="responsive-image"/></a>
                                    </div>)
                            })
                        }
                    </div>
                </div>);
    }

    selectSize = urls => {
        return urls.reduce(function (correctSizeUrls, url) {
            if (url.endsWith(sizeEnding)) {
                correctSizeUrls.push(url);
            }
            return correctSizeUrls;
        }, []);
    };

    doLog = ( text, event ) => {
        // this.setState({header: text + '\n' + stringify(event).replace(",","\n")});
        this.setState(state => {
                        const header = text + ':' + event.type + ", " + event.scale+ ", " + event.isFirst + ", " + event.isFinal;
                        let newHeader = this.state.header.slice();
                        console.log(newHeader);
                        newHeader.push(header);
                        return {header: newHeader};
                        }
                    );
    } 

    swipeleft = event => {
        this.doLog("swipeleft", event);
    } 

    swiperight = event => {
        this.doLog("swiperight", event);
    } 

    pinch = event => {
        this.doLog("pinch", event);
    }

    componentDidMount() {
        this.hammer = Hammer(this.gridElement)
        this.hammer.get('pinch').set({ enable: true });
        this.hammer.on("pinch", this.pinch);
        this.hammer.on('swipeleft', this.swipeleft);
        this.hammer.on('swiperight', this.swiperight);
        fetch(url)
            .then(data => data.json())
            .then(data => this.selectSize(data))
            .then(data => this.setState({urls: data}));
    }
}

ReactDOM.render(<App/>, document.getElementById("root"));

header废话的唯一原因是试图揭示这些Hammerjs事件中可用的内容。我正在尝试在移动设备上进行测试,因此使用类似console.log的标头可以帮助我了解发生了什么。

1 个答案:

答案 0 :(得分:0)

我的错误...我应该已经注册了“ pinchEnd”事件。也就是说,我需要更改行

    this.hammer.on("pinch", this.pinch);

    this.hammer.on("pinchend", this.pinch);