What's the proper way of binding touchstart on React JS?

╄→尐↘猪︶ㄣ 提交于 2019-12-18 14:43:31

问题


I am learning React JS and as of now I cannot find any example on the source code, tests or on the official docs. On the docs the touchStart event is said to be supported but handleTouchStart does not work.

The only place I found and example that actually works was on react-touch project.

The following code works, but is this the only way of binding? It looks like a cheap workaround for me.

var MyHeader = React.createClass({
  handleTouchStart: function() {
    console.log('handleTouchStart');
  },
  render: function() {
    return this.transferPropsTo(
        <header onTouchStart={this.handleTouchStart}>{title}</header>
    );
  }
};

What is actually the proper way of doing this?


回答1:


Since React v0.14, you don't have to call React.initializeTouchEvents(true); manually anymore.

http://facebook.github.io/react/blog/2015/10/07/react-v0.14.html#breaking-changes




回答2:


When playing with touch events I added React.initializeTouchEvents(true) to the componentWillMount component lifecycle method and it seemed to work correctly.

var MyHeader = React.createClass({
  componentWillMount: function(){
    React.initializeTouchEvents(true);
  },
  handleTouchStart: function() {
    console.log('handleTouchStart');
  },
  render: function() {
    return this.transferPropsTo(
        <header onTouchStart={this.handleTouchStart}>{title}</header>
    );
  }
};



回答3:


Hy, Iraê!

You have to call React.initializeTouchEvents(true) before any rendering. Check react doc here: http://facebook.github.io/react/docs/events.html#touch-events



来源:https://stackoverflow.com/questions/22059151/whats-the-proper-way-of-binding-touchstart-on-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!