我的ReactMeteor照片组件在窗体内刷新页面

My ReactMeteor Photo component refreshes the page when inside a form

本文关键字:刷新 窗体 ReactMeteor 照片 组件 我的      更新时间:2023-09-26

我有一个像这样的Photo组件:

Photo=ReactMeteor.createClass({
getInitialState:function(){
    return({
        photo:'Camera.png',
        photoClass:'mouseChange'
    });
},
takePicture:function(){
    var that = this;
    MeteorCamera.getPicture({}, function(error,data){
      if(error){
        alert(error.error);
      }else{
        that.setState({photo: data, photoClass:'pictureTaken'});
      }
    });
},
render:function(){
    return(
        <button>
          <img src={this.state.photo} className={this.state.photoClass} onClick={this.takePicture}/>
        </button>
    );
}   
});

当我在表单外使用它时,它会按预期工作。

然而,在表单中,它会在通常请求使用相机的权限时刷新页面。然后它还将页面的url更改为我从未配置过的内容。

在这两种情况下,我都添加了一个<Photo/>标记。课堂上的改变是为了显示比相机按钮大一点的实际图片。

meteor@1.1.6mdg:camera@1.1.4reactjs:react@0.2.4

按钮单击时的默认行为是提交表单,这会导致刷新。您需要防止这种默认行为。点击事件处理程序(在您的例子中是takePicture方法)获取事件作为参数。您需要做的是调用event.prventDefault();

因此,你的takePicture方法的代码应该如下所示:

takePicture: function(event){
    // This will prevent the refresh
    event.preventDefault();
  
    var that = this;
    MeteorCamera.getPicture({}, function(error,data){
      if(error){
        alert(error.error);
      }else{
        that.setState({photo: data, photoClass:'pictureTaken'});
      }
    });
}