为什么reactjs中的功能组件没有实例? [英] why do functional component in reactjs not have instances?

查看:69
本文介绍了为什么reactjs中的功能组件没有实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反应快速入门中,有关引用和功能组件

您不得在功能组件上使用ref属性,因为他们没有实例:

You may not use the ref attribute on functional components because they don't have instances:

function MyFunctionalComponent() {
  return <input />;
}

class Parent extends React.Component {
  render() {
    // This will *not* work!
    return (
      <MyFunctionalComponent
        ref={(input) => { this.textInput = input; }} />
    );
  }
}

我不完全理解上面的陈述和示例.到目前为止,功能和类组件之间的唯一区别是,它们不具有阅读教程的功能,后者可以具有构造函数和生命周期管理函数之类的东西.

I don't fully understand the above statement and the example. So far from reading the tutorials, the only difference between functional and class component is that the latter can have things like constructor and lifecycle management functions.

文档中说功能组件没有实例是什么意思?是因为它们没有 this 指针吗?此限制来自于react还是ES6?

What does the documentation mean when it says functional components don't have instances? Is it because they don't have this pointer? Is this restriction coming from react or ES6?

推荐答案

功能组件在每次虚拟DOM更新时从上到下重新呈现.由于它们是简单的纯函数,因此它们仅接受属性并输出一段虚拟DOM.它们的寿命仅限于一个渲染器.

Functional components are re-rendered from top to bottom on each virtual DOM update. Since they are simple pure function, they just accept properties and output a piece of virtual DOM. Their lifespan is limited to a single render.

默认的React组件扩展了React.component类,因此它们继承了诸如生命周期挂钩和内部状态管理之类的功能.这些功能允许组件在渲染之间保持其状态并相应地表现.从这种意义上讲,我将它们称为具有实例的组件.

Default React components extend React.component class, so they inherit features like lifecycle hooks and internal state management. Those features allow the component to keep their state between renders and to behave accordingly. In that sense, I would call them components which have an instance.

这篇关于为什么reactjs中的功能组件没有实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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