如何在React中创建对象的新实例?

The*_*orm 10 javascript oop function object reactjs

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

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

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

cardOne // Card {rank: "3", suit: "H"}
Run Code Online (Sandbox Code Playgroud)

那么我将如何在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);
  };

}
Run Code Online (Sandbox Code Playgroud)

(暂时不显示渲染方法)

但是我怎样才能得到正确的反应呢?React内部如何处理函数?(键值对?)以及如何定义对象等?

小智 10

有点晚了,但还是……

自 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"
Run Code Online (Sandbox Code Playgroud)

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

const Card = (rank, suit) => { return { rank: rank, suit: suit } }
Run Code Online (Sandbox Code Playgroud)

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

const cardOne = Card('3', 'H')

cardOne // {rank: "3", suit: "H"}
cardOne.rank // "3"
cardOne.suit // "H"
Run Code Online (Sandbox Code Playgroud)

您还可以在常量前面添加,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"
Run Code Online (Sandbox Code Playgroud)

另外,您应该更好地使用constandlet来声明变量,而不是var因为提升。是一篇很好的文章,解释了原因。


Jag*_*yay 8

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

export class Card {
  constructor(rank, suit) {
    this.rank = rank;
    this.suit = suit;
  }
}
Run Code Online (Sandbox Code Playgroud)

之后,您可以将该模型导入为react组件,如下所示:

import {Card} from './card'
Run Code Online (Sandbox Code Playgroud)


pab*_*han 3

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

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

class ReactApp extends React.Component{ ... }
Run Code Online (Sandbox Code Playgroud)

解决这个问题的另一种方法是简单地使用 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