简体   繁体   English

从高阶组件返回的组件是否称为闭包?

[英]Are the components returned from higher-order components called closures?

I have a higher-order component FormBuilder like this:我有一个像这样的高阶组件FormBuilder

const FormBuilder = (WrappedComponent) => {
  const name = 'bob';

  return class HOC extends React.Component {
    render() {
      return (
        <div> 
          <WrappedComponent {...props} />
        </div>
      );
    }
  }
}

I am thinking that the HOC component that is being returned from this function can be thought of as a closure because it has access to its props(own scope), variable name and component WrappedComponent (outer function's scope) as well as anything defined in the global scope.我认为从这个函数返回的HOC组件可以被认为是一个闭包,因为它可以访问它的 props(自己的作用域)、变量name和组件WrappedComponent (外部函数的作用域)以及任何定义在全球范围。 Anyone can verify whether my thinking is right?谁能验证我的想法是否正确?

Yes component return from higher level component (HOC) can be treated as closure.是的,从更高级别组件 (HOC) 返回的组件可以视为关闭。 With the help of closure we can maintain state by storing value in a variable which can be accessible by inner function.在闭包的帮助下,我们可以通过将值存储在内部函数可以访问的变量中来维护状态。 In case of higher order component as well we can maintain state by defining state at higher level component and can pass that state to low level component and by calling event function on props we can send data back to Higher Order Component.在高阶组件的情况下,我们也可以通过在高级组件上定义状态来维护状态,并将该状态传递给低级组件,并通过调用道具上的事件函数,我们可以将数据发送回高阶组件。

Difference: In case of closure we don't have a control on conditional rendering.区别:在关闭的情况下,我们无法控制条件渲染。 If we want to render only child component we can easily do in case of higher order component by ShouldComponentUpdate() life cycle method but we can't do in closure.如果我们只想渲染子组件,我们可以通过 ShouldComponentUpdate() 生命周期方法轻松地在高阶组件的情况下完成,但我们不能在闭包中完成。 In case of closure function2, function3, function4 have access to variable x在关闭函数2、函数3、函数4的情况下可以访问变量x

 function1(){ var x = 4; return function2(){ return function3(){ return function4(){ } } } }

In case of higher order component we have a control on what data to send to lower component.在高阶组件的情况下,我们可以控制将哪些数据发送到低阶组件。 We can make x available to function1 and function2 by sending as props but we have option not to send to function3 as well as function4.我们可以通过作为 props 发送来使 x 可用于 function1 和 function2,但我们可以选择不发送到 function3 和 function4。 In this way we can have more control in case of higher order component.通过这种方式,我们可以在高阶组件的情况下有更多的控制。 All the component will have there own copy of x variable.所有组件都将拥有自己的 x 变量副本。

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

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