【问题标题】:Instance in ReactReact 中的实例
【发布时间】:2018-11-02 12:36:34
【问题描述】:

有人可以帮助我了解这是否会被归类为实例。

所以如果我得到了正确的一般定义,这将是一个实例是 javascript 中的一个函数的实例

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

//Creating an instance 
var myFather = new Person("John", "Doe", 50, "blue");

现在在 react 中,考虑我们在 React 中的 App.js 文件

import React, { Component } from "react";
import Ccockpit from "../components/cockpit/cockpit.js";

class App extends Component {
  //State

  //All the handlers

  //Render
  render() {
    return (
      <Ccockpit
        coatiitle={this.props.title}
        cocPersonState={this.state.showPerson}
        cocperson={this.state.person.length}
        toggler={this.togglerPersonHandler}
        login={this.loginHandler}
      >
        {person}
      </Ccockpit>
    );
  }
}

这里会不会将&lt;Ccockpit视为我们应用的实例?

【问题讨论】:

  • 您正在创建一个 Ccockpit 实例,所以是的。您可以在代码中创建多个 Ccockpit 元素,每个元素都是一个实例。
  • 我宁愿说 用函数构造的实例,但在 react 示例中,从技术上讲,您并不构造 Ccockpit,您只需将其传递给 react,react 这样做是为了你。所以&lt;Ccockpit /&gt;Ccockpit 的“一种实例”
  • 是的。 React 将调用你的 React 类的构造函数:reactjs.org/docs/react-component.html#constructor
  • Cockpit 不是 App 的实例,它只是 App 渲染的东西(Ccockpit 渲染函数的结果)。然而 Cockpit 对象在后台被实例化为 React 渲染你的应用程序。就叫它 Cockpit,我们不倾向于在 JavaScrpt 中做 C 前缀,而在 React 中我们有时会在类和函数之间更改组件(组件可以是函数而不仅仅是类)

标签: javascript reactjs


【解决方案1】:

Ccockpit 这里会被视为我们 App 的实例吗?

只是为了澄清-您使用的是 JSX 语法,该语法后来被 Babel 转译并被 React 用于创建对象的实例。这个:

class ComponentOne extends React.Component {
  render() {
    return <p>Hello!</p>
  }
}

const ComponentTwo = () => <p>Hello!</p>

function ComponentThree() {
  return (
    <div>
      <ComponentOne />
      <ComponentTwo />
    </div>
  )
}

<ComponentThree />

将被转译to this:

class ComponentOne extends React.Component {
  render() {
    return React.createElement(
      "p",
      null,
      "Hello!"
    );
  }
}

const ComponentTwo = () => React.createElement(
  "p",
  null,
  "Hello!"
);

function ComponentThree() {
  return React.createElement(
    "div",
    null,
    React.createElement(ComponentOne, null),
    React.createElement(ComponentTwo, null)
  );
}

React.createElement(ComponentThree, null);

实例是concrete Object in memory

const a = {};
const b = {};
const c = {};

a, bc 是 Object 实例。他们有自己的记忆空间。换句话说:

<Ccockpit />
<Ccockpit />
<Ccockpit />

这将创建三个使用 Cockpit 构造函数构造的 Object 实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2021-07-12
    • 2020-10-04
    • 1970-01-01
    • 2019-08-12
    相关资源
    最近更新 更多