老师您好,我把category item封装成了两个类,然后进行展示;我想问类定义属性的时候,可以指定对应的类型吗?还有如果是json串,怎么转成对应的类啊?

来源:3-2 第一个展示型组件 - 价格列表

游浪踏

2018-12-19

类category

class Category {
    constructor(id, name, type) {
        this.id = id
        this.name = name
        this.type = type
    }

    juedyType() {
        return this.type === "income" ? "+" : "-"
    }

}

export default Category

Price

category可以指定为上面的那个类的类型吗?

class Price {
    constructor(id, title, price, date, category) {
        this.id = id
        this.title = title
        this.price = price
        this.date = date
        this.category = category
    }
}

export default Price

app类

items 如果是后前接收的json串,怎么转成对应的price类型呢

import React, {Component} from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import './App.css';
import PriceList from './components/PriceList'
import Price from './pojos/Price';
import Category from './pojos/Category'

let category1 = new Category(1, "旅行", "outcome");
let price1 = new Price(1, "去云南旅游", "200", "2018-12-18", category1);
const items = [price1]

class App extends Component {
    render() {
        return (
            <div className="">
                <h1 className="App-title">Welcome to React</h1>
                <PriceList items={items} onDeleteItem={this.onDeleteItem} onModifyItem={this.onDeleteItem}/>
            </div>
        );
        this.onModifyItem = this.onModifyItem.bind(this)
        this.onDeleteItem = this.onDeleteItem.bind(this)
    }

    onModifyItem(item, event) {
        console.log(item)
        console.log(event)
    }

    onDeleteItem(item, event) {
        console.log(item)
        console.log(event)
    }
}

export default App;

写回答

1回答

张轩

2018-12-19

你好 同学 谢谢提问 把数据抽象成一个类做法也很有想法,说明你在很认真的学习。 先支出一个小问题,Category 类里面有个 typo:juedyType 这个单词写错了哈,可以改改。

第一个问题:

category可以指定为上面的那个类的类型吗?

可以,但是使用的时候 item.category 就不是一个简单的 JSON 了,要注意是否会引发一些问题。我建议在类上面 添加一个 方法 toJSON(), 把 JSON 数据返回出来。想使用原始数据的话可以调用。


第二个问题:

如果是json串,怎么转成对应的类啊?


那就要手动转成你的类了,比如说:

const itemsWithClasses = items.map(item => {
    const category = new Category(item.cid, ...省略)
    return new Price(item.id ...太长省略, category)
})


0
3
游浪踏
看了第四节,我知道啦,要用typescript;以前一直是做后端java的,我还是比较习惯用typescript一些,谢谢啦
2018-12-21
共3条回复

React16组件化+测试+全流程 实战在线账本项目

轻松上手,从设计图到上线,精通组件化思维和组件测试

709 学习 · 177 问题

查看课程