React中至少需要一个道具

Kou*_*sha 26 javascript reactjs

我需要至少制作一个所需的道具:

MyComponent.propTypes = {
   data: PropTypes.object,
   url: PropTypes.string
};
Run Code Online (Sandbox Code Playgroud)

因此,在上面的例子中,必须提供data或者url必须提供.这里的用例是用户可以提供data或者url.如果url提供了,那么组件将获取data.

奖金问题:我如何做至少一个道具vs只有一个道具?

fin*_*req 33

PropTypes实际上可以将自定义函数作为参数,因此您可以执行以下操作:

MyComponent.propTypes = {
  data: (props, propName, componentName) => {
    if (!props.data && !props.url) {
      return new Error(`One of props 'data' or 'url' was not specified in '${componentName}'.`);
    }
  },

  url: (props, propName, componentName) => {
    if (!props.data && !props.url) {
      return new Error(`One of props 'url' or 'data' was not specified in '${componentName}'.`);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这允许客户错误消息.使用此方法时,只能返回null或Error

你可以在这里找到更多信息

https://facebook.github.io/react/docs/typechecking-with-proptypes.html#react.proptypes

来自反应文档:

// 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(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },
Run Code Online (Sandbox Code Playgroud)


Bea*_*ith 15

@ finalfreq解决方案的更简洁版本:

const requiredPropsCheck = (props, propName, componentName) => {
  if (!props.data && !props.url) {
    return new Error(`One of 'data' or 'url' is required by '${componentName}' component.`)
  }
}

Markdown.propTypes = {
  data: requiredPropsCheck,
  url: requiredPropsCheck,
}
Run Code Online (Sandbox Code Playgroud)