如何在React中为对象对象定义prop验证规则?

时间:2016-04-25 08:25:51

标签: javascript reactjs

当道具是记录对象时,例如:

const pets = {
    "P001": { id: "P001", name: "Jim",  type: "Dog" },
    "P002": { id: "P002", name: "Jack", type: "Cat" },
    "P003": { id: "P003", name: "Jill", type: "Dog" },
};

如何验证这是x形状的“键控”数组?

尝试失败

我想定义验证规则:

pets: React.PropTypes.arrayOf(React.PropTypes.shape({
    id:   React.PropTypes.string,
    name: React.PropTypes.string,
    type: React.PropTypes.string
}))

这当然失败了,因为它正在寻找:

const pets = [
    { id: "P001", name: "Jim",  type: "Dog" },
    { id: "P002", name: "Jack", type: "Cat" },
    { id: "P003", name: "Jill", type: "Dog" }
];

尝试失败

pets: React.PropTypes.shape(React.PropTypes.shape({
    id:   React.PropTypes.string,
    name: React.PropTypes.string,
    type: React.PropTypes.string
}))

这当然也失败了,因为它正在寻找:

const pets = {
    { id: "P001", name: "Jim",  type: "Dog" }
};

1 个答案:

答案 0 :(得分:0)

您需要customArrayProp。

offers.php

见这里。 https://facebook.github.io/react/docs/reusable-components.html