Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React Components, Elements, and Instances #10

Open
jiaoguanwen opened this issue Nov 5, 2020 · 0 comments
Open

React Components, Elements, and Instances #10

jiaoguanwen opened this issue Nov 5, 2020 · 0 comments

Comments

@jiaoguanwen
Copy link
Owner

jiaoguanwen commented Nov 5, 2020

React Components, Elements, and Instances

组件,他们的实例和元素之间的区别,困扰着很多React新手。为什么有3个不同的术语来指代绘制在屏幕上的东西?

管理实例

如果你刚接触React,你之前可能工作中只用到组件类和实例。比如,你可能通过创建一个类声明了一个按钮Button组件。当app运行时,你可能会有多个这个组件的实例在屏幕上,每一个都有它自己的属性和本地状态。这是传统的面向对象UI编程。那为什么要介绍元素呢?

在传统的UI模型中,关注创建和销毁子组件实例取决于你自己。如果一个表单组件想要渲染一个按钮组件,他需要创建一个他的实例,然后手动的保持它和新信息的更新。

class Form extends TraditionalObjectOrientedView {
  render() {
    // Read some data passed to the view
    const { isSubmitted, buttonText } = this.attrs;

    if (!isSubmitted && !this.button) {
      // Form is not yet submitted. Create the button!
      this.button = new Button({
        children: buttonText,
        color: 'blue'
      });
      this.el.appendChild(this.button.el);
    }

    if (this.button) {
      // The button is visible. Update its text!
      this.button.attrs.children = buttonText;
      this.button.render();
    }

    if (isSubmitted && this.button) {
      // Form was submitted. Destroy the button!
      this.el.removeChild(this.button.el);
      this.button.destroy();
    }

    if (isSubmitted && !this.message) {
      // Form was submitted. Show the success message!
      this.message = new Message({ text: 'Success!' });
      this.el.appendChild(this.message.el);
    }
  }
}

这些是伪代码,但是它或多或少结束了当你写组合UI时一贯的面向对象的方式比如使用Backbone类库。

每一个组件实例都必须保持着他对DOM节点和子组件实例的引用,然后在合适的时机创建、更新和销毁它们。代码行数的增长是组件可能状态数量的平方,父组件对它们的子组件实例有着直接的控制,这就使得想要在未来分开他们很难。

那么React是怎么不同于此的呢?

元素描述着树

在React中,这里是元素来解决这个问题。元素是一个描述组件实例或者DOM节点和它期望的属性的对象字面量。他只包含组件类型(例如,一个Button),他的属性(例如,他的color),以及他里面的每一个子元素等信息。

一个元素不是一个实际的实例。有点像一种你告诉React你希望屏幕上展示什么的方式。你不能调用元素伤的任何方法。他只是一个拥有两个字段type(string | ReactClass)和props(Object)的不变的描述对象。

DOM元素

总结

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant