2016-04-25 25 views
2

当道具是记录一个对象,如:如何为React中的对象定义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" } 
}; 

回答

1

你需要一个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

+0

我希望有一个更通用的方法来处理这个问题 - 我想我可以创建一个通用函数来传入 – Chris