2016-03-29 11 views

Antwort

3

Es ist nicht bequem, aber es ist möglich, einen eigenen PropType zu schreiben.

Von der Quelle der Reaktion (die es leider nicht an dieser Stelle aussetzt):

function createChainableTypeChecker(validate) { 
    function checkType(isRequired, props, propName, componentName, location, propFullName) { 
    componentName = componentName || ANONYMOUS; 
    propFullName = propFullName || propName; 
    if (props[propName] == null) { 
     var locationName = ReactPropTypeLocationNames[location]; 
     if (isRequired) { 
     return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.')); 
     } 
     return null; 
    } else { 
     return validate(props, propName, componentName, location, propFullName); 
    } 
    } 

    var chainedCheckType = checkType.bind(null, false); 
    chainedCheckType.isRequired = checkType.bind(null, true); 

    return chainedCheckType; 
} 

, die Sie mögen so verwenden können:

const map = createChainableTypeChecker(function(props, propName, componentName, location, propFullName) { 
    if (...) { 
     return null; // pass the check 
    } 
    return new Error('Error message'); // fail the check 
}); 
1

Versuchen Sie eine benutzerdefinierte Eigenschaft Validator-Funktion (von der documentation):

// You can also specify a custom validator. It should return an Error 
// object if the validation fails. Don't `console.warn` or throw, as this 
// won't work inside `oneOfType`. 
customProp: function(props, propName, componentName) { 
    if (!/matchme/.test(props[propName])) { 
    return new Error('Validation failed!'); 
    } 
} 

das könnte so etwas wie folgt aussehen:

static propTypes = { 
    elementMap: (props, propName) => { 
     const m = props[propName]; 
     if (!m) { return new Error(`Required property ${propName} not supplied`); } 
     if (!(m instanceof Map)) { return new Error("must be a Map"); } 
     // check contents of map if you want... 
    }, 
}; 
+0

Und wie kann ich ein Array von diesen beispielsweise angeben, oder eine PropTypes.Shape mit diesem PropType innen? –

+0

Speichern Sie diese Funktion als Variable (z. B. 'MyPropTypes.mapRequired') und verwenden Sie' MyPropTypes.mapRequired', wo auch immer Sie einen anderen Prop-Typ wie 'PropType.string' verwenden. – Brandon

4
elementsMap: p.instanceOf(Map).isRequired 
Verwandte Themen