【问题标题】:How to create an new instance of an Object in React?如何在 React 中创建对象的新实例?
【发布时间】:2017-04-25 04:27:50
【问题描述】:

显然在普通的 JS 中我可以做到这一点

var Card = function(rank, suit){
    this.rank = rank; 
    this.suit = suit
  }

var cardOne = new Card('3', 'H');

cardOne // Card {rank: "3", suit: "H"}

那么我将如何在 react 和 ES6 领域做到这一点?

我尝试过这样的事情:

class ReactApp extends React.Component{

  Card = (rank, suit) => {
    this.rank = rank;
    this.suit = suit;
  };

  createCard = () => {
    let CardObj = {};
    let card = new this.Card('3', 'Hearts');
    console.log(card);
  };

}

(暂时不显示渲染方法)

但是我怎样才能让它在反应中记录正确的东西呢? React 内部如何处理函数? (键值对?)以及如何定义对象等?

【问题讨论】:

  • 你到底想在这里实现什么?您可以定义一个函数并将其命名为Card,然后在您的ReactApp 类中实例化它,就像您在new Card(rank, suit) 之前所做的那样。
  • 好像你在谈论一个组件?创建一个名为 Card 的组件,就像使用 ReactApp 一样。

标签: javascript function oop object reactjs


【解决方案1】:

如果您询问定义只包含数据的类,那么这只是一个 ES6 问题,而不是特定于 React 的问题。简单的答案是将Card 类与您的组件分开声明,例如。 g.

class Card {
  constructor(rank, suit) {
    this.rank = rank;
    this.suit = suit;
  }
}

class ReactApp extends React.Component{ ... }

解决此问题的另一种方法是简单地使用 ES5(也称为“普通 javascript”),因为我假设您更熟悉它。使用 React 并不强制你使用 ES6。

这里是关于 ES6 的有用文章列表:https://hacks.mozilla.org/category/es6-in-depth/

这里是关于在 React 中使用 ES5 的信息:https://facebook.github.io/react/docs/react-without-es6.html

【讨论】:

    【解决方案2】:

    如果你正在寻找 Card 模型,你可以为它创建一个新的 ES6 类

    export class Card {
      constructor(rank, suit) {
        this.rank = rank;
        this.suit = suit;
      }
    }
    

    在此之后,您可以将该模型导入到 react 组件中

    import {Card} from './card'
    

    【讨论】:

      【解决方案3】:

      有点晚了,不过还是……

      自从引入钩子的 React v16.8 以来,建议使用功能组件而不是类组件。

      const Card = function(rank, suit) {
          const rank = rank;
          const suit = suit;
          return { rank, suit };
      };
      
      const cardOne = Card("3", "H");
      
      cardOne; // {rank: "3", suit: "H"}
      cardOne.rank; // "3"
      cardOne.suit; // "H"
      

      但这有点过时了。使用箭头函数在一行代码中执行此操作的最优雅方式:

      const Card = (rank, suit) => { return { rank: rank, suit: suit } }
      

      就是这样。现在您可以分配变量了。

      const cardOne = Card('3', 'H')
      
      cardOne // {rank: "3", suit: "H"}
      cardOne.rank // "3"
      cardOne.suit // "H"
      

      您还可以在常量前面添加export,使其可从任何地方导入:

      // components.js
      export const Card = (rank, suit) => { return { rank: rank, suit: suit } }
      
      
      // App.js
      import { Card } from './components'
      
      const cardTwo = Card('2', 'F')
      cardTwo // {rank: "2", suit: "F"}
      cardTwo.rank // "2"
      cardTwo.suit // "F"
      

      另外你最好使用constlet 来声明变量而不是var 因为提升。 Here 是一篇很好的文章,可以解释原因。

      【讨论】:

        猜你喜欢
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-18
        相关资源
        最近更新 更多