当使用“null”参数绑定React组件中的事件回调函数时,“this”是指什么?

时间:2017-04-21 08:45:07

标签: javascript reactjs bind dom-events

this React tutorial中,React演示组件内的按钮单击事件回调函数明确绑定到if(isset($_POST["upload_report"])) { echo $_POST['title']; // giving title index undefined $max_report_id += 1; $target_dir = "Reports/"; $file_title = mysqli_real_escape_string($connection,trim($_POST['title'])); $file_name = mysqli_real_escape_string($connection,trim($_FILES['report']["name"])); //$file_size = mysqli_real_escape_string($connection,trim($_FILES['report']["size"])); $target_file = $target_dir . basename($file_name); //basename gets filename from path $uploadOk = 1; $file_type = pathinfo($target_file,PATHINFO_EXTENSION); $target_file = $target_dir . $max_report_id . "." . $file_type; // Check if file already exists if (file_exists($target_file)) { //echo "Sorry, file already exists."; $uploadOk = 0; } /* Check file size if ($file_size > 5000000) { echo "Sorry, your file is too large."; $uploadOk = 0; } */ // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { $status_fail = true; $fail_message = "Sorry, there was an error uploading your file."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["report"]["tmp_name"], $target_file)) { $status_success = true; $success_message = "The file ". $file_title. " has been uploaded."; $query = "insert into reports(title,fname,path,platform,added_by,added_on) values ('$file_title','$file_name','$target_file','$platform','$user_id',now())"; $result = mysqli_query($connection, $query) or die($query); } else { $status_fail = true; $fail_message = "Sorry, there was an error uploading your file."; } } }

null

但是,在回调函数中,<button onClick={_this.props.toggleActive.bind(null, user.id)}>Toggle Active</button> 关键字用于访问React Container Component的状态:

this

我不明白为什么当toggleActive: function(userId) { ... var newState = Object.assign({}, this.state) ... } 应该等于this时这个例子有效,或者在非严格模式下,全局null对象。任何人都可以告诉我为什么这个例子仍在运作?

可以找到相应的Codepen here

2 个答案:

答案 0 :(得分:0)

<button onClick={_this.props.toggleActive.bind(null, user.id)}>Toggle Active</button>
  

这里你是null的绑定方法,而不是实例。你可以   不能在方法中访问this,因此this将无效。

答案 1 :(得分:0)

我之前错了,并没有理解这个问题。请看下面的代码: -

function a(){
    this.x = 5;
    this.y = function(){
        console.log(this.x)
    }
}
var x = 20;
var c = new a();
var d = c.y.bind(null);
d(); // prints 20 and not null or undefined

当null作为绑定函数中的上下文传递时,该函数保留其原始上下文,即此处的全局范围(定义函数d的上下文)。但是,如果在绑定函数中传递了某个上下文,则该函数将打印&#39; X&#39;该背景的财产。

同样,在

中传递null时
<button onClick={_this.props.toggleActive.bind(null, user.id)}>Toggle Active</button>

在触发器上,toggleActive函数内的上下文是定义它的上下文,即UserListContainer.Hence,它能够访问其状态