特定子组件的PropTypes

问题描述 投票:0回答:1

我正在努力弄清楚如何为一组特定的子组件指定PropTypes。我的对话框组件允许获取Title,Body和/或Footer类型的组件。所有这些组件只能使用一次,但可以同时出现。

是否有建议的方法来指定适当的PropType?

const Title = ({ text }) => (
  <h1>{ text }</h1>
);

const Body = ({ text }) => (
  <p>{ text }</p>
);

const Footer = ({ text }) => (
  <small>{ text }</small>
);

const Dialog = ({ children }) => (
  React.Children.map(children, (child) => {
    return (
      <div>{child}</div>
    )
  })
);

Dialog.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.instanceOf(Title),
    PropTypes.instanceOf(Body),
    PropTypes.instanceOf(Footer)
  ]).isRequired
}
reactjs react-proptypes
1个回答
0
投票

你正在使用Dialog作为<Dialog>{children}</Dialog>吗?

那么..我不知道这样做是否是好习惯。最具体的是更具体。

你为什么不这样做:

const Dialog = ({ title, children, footer }) => (
    <div>
        { title } 
        { children }
        { footer }
    </div>
)

Dialog.propTypes = {
    title: PropTypes.element,
    footer: PropTypes.element,
    children: PropTypes.any.isRequired
}

并使用它像:

const Title = ({ text }) => (
  <h1>{ text }</h1>
)

const Footer = () => (
  <small>Dialog Footer</small>
)


<Dialog
    title={ <Title text="Dialog Title" /> }
    footer={ <Footer /> }
>
    <p>Body here</p>
</Dialog>

或者,如果页脚和标题确实需要是特定组件的实例,可能这样:


const Title = ({ children }) => (
  <h1>{ children }</h1>
)

const Footer = () => (
  <small>Dialog Footer</small>
)

const Dialog = ({ title, children, showFooter }) => (
    <div>
        { title && <Title>{title}</Title> } 
        { children }
        { showFooter && <Footer />  }
    </div>
)

Dialog.propTypes = {
    title: PropTypes.string,
    showFooter: PropTypes.bool,
    children: PropTypes.any.isRequired
}

并使用它像:

<Dialog
    title="Dialog title"
    showFooter={true}
>
    <p>Body here</p>
</Dialog>

你可以在这里检查可用的道具类型https://reactjs.org/docs/typechecking-with-proptypes.html

© www.soinside.com 2019 - 2024. All rights reserved.