javascript - ReactJs 调用 {this.functionName} 和 {this.functionName()} 有什么区别

标签 javascript html reactjs

我已经使用 ReactJs 几天了。我发现有些语法有点奇怪。 例如,有时我必须这样调用函数:

{this.functionName}

末尾没有括号

有时我必须这样调用它:

{this.functionName()}

就像这个例子:

  <button onClick={this.streamCamVideo}>Start streaming</button>
  <h1>{this.logErrors()}</h1>

查看调用 this.streamCamVideothis.logErrors() 之间的区别。
有人可以为此提供解释吗?

编辑1: 根据要求,以下是它们的定义:

  streamCamVideo() {
    var constraints = { audio: true, video: { width: 1280, height: 720 } };
    navigator.mediaDevices
      .getUserMedia(constraints)
      .then(function(mediaStream) {
        var video = document.querySelector("video");

        video.srcObject = mediaStream;
        video.onloadedmetadata = function(e) {
          video.play();
        };
      })
      .catch(function(err) {
        console.log(err.name + ": " + err.message);
      }); // always check for errors at the end.
  }
 logErrors(){
      return(navigator.mediaDevices.toString())
  }

最佳答案

{this.streamCamVideo}是对 streamCamVideo 的引用功能。你可以想到this.streamCamVideo作为一个变量,其值为函数。像这样思考一下:

const myVariable = 'some text'

const myOtherVariable = function() {
  console.log("You are inside the myOtherVariable function");
}

两者myVariablemyOtherVariable是变量。一个具有字符串的值,另一个具有函数的值。假设您想将这两个变量传递给另一个函数:

const anotherVariable = function(aStringVariable, aFunctionVariable) {
  console.log(aStringVariable, aFunctionVariable)
}

anotherVariable(myVariable, myOtherVariable)

您可能会看到类似这样的内容记录到控制台:

some text
[Function]

请注意,您永远不会看到控制台中记录的文本“您位于 myOtherVariable 函数内部”。那是因为myOtherVariable函数从未被调用。它刚刚传递到anotherVariable功能。为了调用该函数,您需要执行以下操作:

const anotherVariable = function(aStringVariable, aFunctionVariable) {
  aFunctionVariable()
  console.log(aStringVariable, aFunctionVariable)
}

注意aFunctionVariable()后面的括号?这就是实际调用函数的样子。因此,在这种情况下,您会看到类似这样的内容记录到控制台:

You are inside the myOtherVariable function
some text
[Function]

该函数实际上正在被调用。

所以在你的例子中:

<button onClick={this.streamCamVideo}>Start streaming</button>
<h1>{this.logErrors()}</h1>

this.streamCamVideo只是作为变量传递给 <button>元素。单击按钮时,无论已分配给onClick,将被执行。此时,您作为变量传递的函数将被实际调用。

另外,请注意this.logErrors()后面的括号? logErrors函数正在执行。它没有作为变量传递给任何东西。

关于javascript - ReactJs 调用 {this.functionName} 和 {this.functionName()} 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59588732/

相关文章:

javascript - Jquery toggleActive 不起作用

javascript - React-dropzone - 访问通过点击而不是删除添加的文件

javascript - 将 "boolean bit array"转换为 Typescript 中的数字

javascript - 正则表达式排除JavaScript中的特定网站?

javascript - 如何更改 Canvas 的 'x' 和 'y'?

html - 如何在使用 md 对话框时禁用背景?

javascript - XHR加载失败: POST on AJAX request (in React)

javascript - 如何在 react 组件中嵌入谷歌地图

javascript - 在最小化浏览器窗口的同时重新调整 Kendo 图表的大小?

javascript - 调整大小时 Chart.js 模糊