Подтвердить что ты не робот

Реагировать реквизит - установить isRequired на опоре, если другая опора равна нулю/пустой

У меня есть компонент <Button>.
Если у компонента нет this.props.children, я хочу установить prop ariaLabel как isRequired, иначе in может быть необязательным. Как это сделать?

ariaLabel prop не требуется:

<Button>Add to bag</Button>

Требуется

ariaLabel prop:

<Button ariaLabel="Add to bag" icon={ favorite } />

, если this.props.children и this.props.ariaLabel пусты, он выдает ошибку, говоря, что this.props.ariaLabel есть isRequired

<Button icon={ favorite } />

propTypes:

Button.propTypes = {
    /** icon inside Button. */
    icon: React.PropTypes.object,
    /** Content inside button */
    children: React.PropTypes.node,
    /** Aria-label to screen readers */
    ariaLabel: React.PropTypes.string, /*isRequired if children is empty */
};

Спасибо

4b9b3361

Ответ 1

Вам не нужна другая библиотека, "prop-types" предоставляет это из коробки. Смотрите https://facebook.github.io/react/docs/typechecking-with-proptypes.html

Пример:

import PropTypes from 'prop-types';

//.......    

ExampleComponent.propTypes = {
    showDelete: PropTypes.bool,
    handleDelete: function(props, propName, componentName) {
        if ((props['showDelete'] == true && (props[propName] == undefined || typeof(props[propName]) != 'function'))) {
            return new Error('Please provide a handleDelete function!');
        }
    },

}

Ответ 2

Это может быть именно то, что вам нужно: https://github.com/thejameskyle/react-required-if

В вашем случае ваши propTypes будут:

import requiredIf from 'react-required-if';

Button.propTypes = {
    /** icon inside Button. */
    icon: React.PropTypes.object,
    /** Content inside button */
    children: React.PropTypes.node,
    /** Aria-label to screen readers */
    ariaLabel: requiredIf(React.PropTypes.string, props => !props.children), /*isRequired if children is empty */
};

Ответ 3

Чтобы добавить ответ @chickenchilli выше, вы можете абстрагировать его в более удобную вспомогательную функцию, например:

conditionalPropType.js

export default function conditionalPropType(condition, message) {
  if(typeof condition !== 'function') throw "Wrong argument type 'condition' supplied to 'conditionalPropType'";
  return function(props, propName, componentName) {
    if (condition(props, propName, componentName)) {
      return new Error('Invalid prop '${propName}' '${props[propName]}' supplied to '${componentName}'. ${message}');
    }
  }
}

MyComponent.js

import PropTypes from 'prop-types';
import conditionalPropType from './conditionalPropType';

[...]

MyComponent.propTypes = {
  conditionProp: PropTypes.bool,
  dependentProp: conditionalPropType(props => (props.condition && typeof(props.someProp) !== 'boolean'), "'dependentProp' must be boolean if 'conditionProp' is true"),
};