Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript react prop type:现有prop类型的可重用验证器_Javascript_Reactjs_React Proptypes - Fatal编程技术网

Javascript react prop type:现有prop类型的可重用验证器

Javascript react prop type:现有prop类型的可重用验证器,javascript,reactjs,react-proptypes,Javascript,Reactjs,React Proptypes,在React中使用prop类型时,有没有一种方法可以从现有的验证器创建可重用的验证器 示例:验证标题具有标题和图标的“标题”对象: Component.propTypes = { header: PropTypes.shape({ title: PropTypes.string.isRequired, icon: PropTypes.element, }) } 我们可以编写一个可重用的isHeader函数,而不是在道具沿着组件链传递时重复此操作吗 Component

在React中使用prop类型时,有没有一种方法可以从现有的验证器创建可重用的验证器


示例:验证标题具有标题和图标的“标题”对象:

Component.propTypes = {
  header: PropTypes.shape({
    title: PropTypes.string.isRequired,
    icon: PropTypes.element,
  })
}

我们可以编写一个可重用的isHeader函数,而不是在道具沿着组件链传递时重复此操作吗

Component.propTypes = {
  header: isHeader
}

您可以使用以下内容:

export const shared = {
  header: PropTypes.shape({
    title: PropTypes.string.isRequired,
    icon: PropTypes.element,
  })
}
然后:

Component.propTypes = {
  {...shared}
}

您应该能够像这样创建可重用类型:

const myReusableHeader = PropTypes.shape({
  title: PropTypes.string.isRequired,
  icon: PropTypes.element,
})
Component.propTypes = {
  header: myReusableHeader
}
然后您可以在组件中使用它,如下所示:

const myReusableHeader = PropTypes.shape({
  title: PropTypes.string.isRequired,
  icon: PropTypes.element,
})
Component.propTypes = {
  header: myReusableHeader
}