简体   繁体   English

在 React Native 中使用构造函数创建 Object

[英]Creating Object with Constructor in React Native

I'm trying to create an RN Object with a constructor passing json object but I'm getting "ReferenceError: Can't find variable: Product".我正在尝试使用传递 json object 的构造函数创建一个 RN Object 但我收到“ReferenceError:找不到变量:产品”。

Product.js产品.js

export default class Product {
    constructor(product) {
        this.name = product.name
        this.items = product.Items
        this.price = product.Price
        this.productID = product.ProductID 
        this.medias = product.Medias
        this.imageSmall = BASE_IMAGES_URL + product.MediaSmall
        this.imageLarge = this.getImageLarge(product.Medias)
    }
}

PDP.js PDP.js

import { Product } from '../models/Product'
class PDP extends Component {
 render() {

    var imagesProd = [];
    var product = new Product(this.props.navigation.state.params.currentProduct);
      ....
}
}

the problem is with new Product() using directly this.props.navigation.state.params.currentProduct works fine.问题在于new Product()直接使用this.props.navigation.state.params.currentProduct工作正常。

EDIT编辑

After your tips, I changed the import to import Product from '../models/Product' but I'm getting根据您的提示,我将导入更改为import Product from '../models/Product'但我得到了

TypeError: TypeError: TypeError: TypeError: undefined is not a constructor (evaluating 'new P.default(s)') TypeError:TypeError:TypeError:TypeError:未定义不是构造函数(评估'new P.default(s)')

The problem is with your import.问题在于您的导入。 You used a default export in Product class so your import should be您在产品 class 中使用了默认导出,因此您的导入应该是

import Product from '../models/Product'

The first line in PDP.js should be import Product from '../models/Product' PDP.js 的第一行应该是import Product from '../models/Product'

Take a look here for few details about import.在这里查看有关导入的一些详细信息。 When should I use curly braces for ES6 import? 什么时候应该使用花括号进行 ES6 导入?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM