如何在React中验证Prop的类及其类的字段(嵌套对象)?

时间:2016-12-02 07:33:28

标签: javascript reactjs react-proptypes

我有一个这样的课程:

class ResponseState() {
   constructor(data) {
      this.data = data;
   }
}

现在我可以验证道具是这种类型的:

Container.propTypes = {
   myProp: PropTypes.instanceOf(ResponseState).isRequired,
};

这很好用,但我怎样才能验证myProp.data的类型?如果我使用PropTypes.shape,那么我无法检查myProp本身。

有一个类似的问题here,但它并没有给出这个确切问题的答案。

1 个答案:

答案 0 :(得分:1)

我很惊讶看不到PropTypes的任何组合形式。

您可以使用自定义验证器:

#include <iostream>
using namespace std;

int main()
{
    char name[99];
    int counter=0; // variable to store the number of characters in name.

    cin >> name;

    // the for loop is counting each letter until the end of the string, storing the result in counter.
    for(;name[counter]!='\0'; counter++)
    {}

    cout << "\nName: ";

    // if the name you entered was "Billy" counter would = 5
    for (;counter > 0; counter--)
    {
        // since counter = 5 counter subtracts 1 to get to the "5th" spot in the array which is when counter = 4
        // name[0] = B
        // name[1] = i
        // name[2] = l
        // name[3] = l
        // name[4] = y
        // now starting from position 4 in the array counter-- subtracts 1 
        // from counter each time it runs through the loop to get to each previous letter.
        cout << name[counter-1];
    }
}