gpt4 book ai didi

javascript - 如何在 React 中为对象的对象定义 Prop 验证规则?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:41:38 26 4
gpt4 key购买 nike

当 Prop 是一个记录的对象时,例如:

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" }
};

最佳答案

您需要一个 customArrayProp。

// You can also supply a custom validator to `arrayOf` and `objectOf`.
// It should return an Error object if the validation fails. The validator
// will be called for each key in the array or object. The first two
// arguments of the validator are the array or object itself, and the
// current item's key.
customArrayProp: React.PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
if (!/matchme/.test(propValue[key])) {
return new Error(
'Invalid prop `' + propFullName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
})

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

关于javascript - 如何在 React 中为对象的对象定义 Prop 验证规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36835377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com