简体   繁体   English

为什么要在函数ReactJS中使用函数?

[英]Why function inside function ReactJS?

There's this piece of code in ReactJS documentation: ReactJS文档中有这段代码:

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

Why for example the same thing couldn't be done like this: 例如为什么为什么不能做这样的事情:

function handleClick(){
    console.log("The component was clicked");
}

function Component(props){
    return <a href="#">Click me</a>
}



ReactDOM.render(<Component onClick={handleClick}/>, document.getElementById('root'));

Can someone help me understand why there has to be two functions or point me in a direction where this would be explained to a beginner? 有人可以帮助我理解为什么必须有两个功能,或者将我的方向告诉初学者吗?

The second version is not going to work because onClick on Component will be interpreted as a prop and not an event handler. 第二个版本不起作用,因为onClick on Component将被解释为prop,而不是事件处理程序。 You could fix it like this: 您可以这样解决:

function handleClick(){
    console.log("The component was clicked");
}

function Component(props){
    return <a href="#" onClick={handlerClick}>Click me</a>
}

ReactDOM.render(<Component />, document.getElementById('root'));

Now, why not use two functions instead of one main with handler inside? 现在,为什么不使用两个函数而不是一个内部带有处理程序的主函数? Well you can but this version lacks code encapsulation. 可以,但是此版本缺少代码封装。 ActionLink in your first version is a concrete unit that embodies everything it needs while in the second snippet, Component is basically useless without additional handleClick function. 第一个版本中的ActionLink是一个具体的单元,体现了所需的一切,而在第二个片段中,没有附加的handleClick函数, Component基本上是无用的。

ActionLink is a component/class type. ActionLink是组件/类类型。 It allows for encapsulation and code reuse of all of the behavior needed for that link. 它允许对该链接所需的所有行为进行封装和代码重用。 If it was a free function, it would loose that OO design tenant. 如果它是一个自由功能,则将失去该OO设计承租人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM