我有一个可能的字段数组:
const io = require('socket.io')(app);
例如export const fields = [
{ type: 'select', defaultValue: MAINTAIN, name: TENDENCY },
{ type: 'select', defaultValue: DISTANT_ACQUAINTANCE, name: GROUP },
{ type: 'input', defaultValue: '', name: FIRST_NAME },
{ type: 'input', defaultValue: '', name: LAST_NAME },
{ type: 'input', defaultValue: '', name: CITY },
{ type: 'input', defaultValue: '', name: COMPANY },
{ type: 'input', defaultValue: '', name: POSITION },
];
。
我将这些字段呈现在const FIRSTNAME = 'firstName';
组件中。我试图像这样进行PropTypes检查:
<ContactCell />
但是当我这样渲染一个ContactCell时:
ContactCell.propTypes = {
field: PropTypes.oneOf(fields).isRequired,
handleChange: PropTypes.func.isRequired,
value: PropTypes.string.isRequired,
};
我得到了错误:
const createContactCell = (props = {}) =>
render(<ContactCell {...props} handleChange={() => {}} />);
const props = {
value: 'Mike',
field: { type: 'input', defaultValue: '', name: 'firstName' },
};
createContactCell(props);
您如何正确地对PropType进行一系列可能的对象检查?
答案 0 :(得分:2)
oneOf
道具类型将检查引用,但是如果要检查所有属性是否与fields
数组中的对象之一匹配,则可以创建一个自定义道具类型,例如使用Lodash isEqual
将prop与fields
数组中的对象进行比较。
const fields = [
{ type: "select", defaultValue: MAINTAIN, name: TENDENCY },
{ type: "select", defaultValue: DISTANT_ACQUAINTANCE, name: GROUP },
{ type: "input", defaultValue: "", name: FIRST_NAME },
{ type: "input", defaultValue: "", name: LAST_NAME },
{ type: "input", defaultValue: "", name: CITY },
{ type: "input", defaultValue: "", name: COMPANY },
{ type: "input", defaultValue: "", name: POSITION }
];
ContactCell.propTypes = {
handleChange: PropTypes.func.isRequired,
value: PropTypes.string.isRequired,
field: function(props, propName, componentName) {
if (
propName === "field" &&
!fields.some(field => _.isEqual(props.field, field))
) {
return new Error(
"Invalid prop `field` supplied to `ContactCell`. Validation failed."
);
}
}
};