首页 > 解决方案 > 特定子组件的 PropTypes

问题描述

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

是否有推荐的方法来指定适当的 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
}

标签: reactjsreact-proptypes

解决方案


已编辑

您可以使用自定义 PropType 验证来检查 prop 值是否符合您的组件期望的规则:组件名称(标题、正文和/或页脚),如果每个组件只有一个,这些组件的顺序...

但这太过分了。

我认为最好的方法是将这些组件放在 Dialog 组件中并使用 props 对其进行自定义。例如:

代码沙盒

const Title = ({ children }) => <h2>{children}</h2>;

const Dialog = ({
  title,
  showConfirmationButton,
  showCancelButton,
  onConfirmation,
  onCancel,
  children
}) => (
  <div>
    {!!title && <Title>{title}</Title>}
    {children}
    {(showConfirmationButton || showCancelButton) && <hr />}
    {showCancelButton && <button onClick={onCancel}>Cancel</button>}
    {showConfirmationButton && <button onClick={onConfirmation}>Ok</button>}
  </div>
);

Dialog.propTypes = {
  title: PropTypes.string,
  showOkButton: PropTypes.bool,
  onClickOk: PropTypes.func,
  children: PropTypes.any.isRequired
};

export default function App() {
  return (
    <Dialog
      title="Title dialog"
      showConfirmationButton
      onConfirmation={() => console.log("ok")}
      showCancelButton
      onCancel={() => console.log("cancel")}
    >
      <p>The Dialog body as children.</p>
    </Dialog>
  );
}

或者,如果您仍然需要将组件作为道具传递,那么最好的应该是:

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

Dialog.propTypes = {
    title: PropTypes.instanceOf(Title),
    footer: PropTypes.instanceOf(Footer),
    body: PropTypes.instanceOf(Body)
}

您可以在此处查看可用的道具类型https://reactjs.org/docs/typechecking-with-proptypes.html


推荐阅读