在JSX中调用javascript函数:为什么不使用()调用函数会起作用? [英] Calling a javascript function in JSX: why does calling a function without the () work?

查看:71
本文介绍了在JSX中调用javascript函数:为什么不使用()调用函数会起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前在Codecademy上,并学习有关React的信息.

Currently on Codecademy and learning about React.

喜欢此代码:

import React from 'react';
import ReactDOM from 'react-dom';

function makeDoggy(e) {
  // Call this extremely useful function on an <img>.
  // The <img> will become a picture of a doggy.
  e.target.setAttribute('src', 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg');
  e.target.setAttribute('alt', 'doggy');
}

const kitty = (
  <img 
    src="https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg" 
    alt="kitty" 
    onClick={makeDoggy}
  />
  	
);

ReactDOM.render(kitty, document.getElementById('app'));

const kitty的onClick属性设置为函数makeDoggy.为此,您必须指出要使用Javascript,因此要使用{}括号.但是正确的答案是使用makeDoggy而不是标准函数调用:makeDoggy().

The onClick attribute of const kitty is set to the function makeDoggy. To do this, you have to indicate you are using Javascript hence the {} brackets.However, the correct answer uses makeDoggy instead of using the standard function call: makeDoggy().

此外,makedoggy函数具有e参数.什么时候传递该参数?当函数需要一个不存在的参数时,如何调用makeDoggy?

Also, the makedoggy function has an e parameter. When does that parameter get passed and how can a call to makeDoggy be made with a nonexsistent parameter when the function requires one?

推荐答案

没有括号,您不会调用该函数.不带括号的函数名称是对该函数的引用.此时在函数中不使用括号,因为我们不是在遇到代码的地方调用函数,而是希望将引用传递给函数.如果您使用makeDoggy(),该函数将在该点被调用,我们希望只在onClick之后调用它,因此我们在此传递对makeDoggy的引用.

Without parenthesis, you're not calling the function. The name of the function without the parenthesis is a reference to the function. Parentheses is not used in the function at that point because we are not calling the function at the point where the code is encountered, but instead want to pass a reference to the function. If you use makeDoggy() , the function will get called at that point, we instead want it to be called only after onClick, so we pass a reference to makeDoggy there.

或者,您可以执行onClick={()=>makeDoggy()}

e使用名为属性初始化程序<的自动绑定/a>在es6中.

e gets bound automatically using something called property initializer in es6.

这篇关于在JSX中调用javascript函数:为什么不使用()调用函数会起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆