reactjs - 特定子组件的 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
}
解决方案
已编辑
您可以使用自定义 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
推荐阅读
- google-apps-script - gmail 插件 contextualTriggers 触发的事件中缺少 Gmail 属性
- google-sheets - 获取 Google Sheet csv 文件会产生 CORS 错误
- javascript - 如何镜像和反转画布对象的运动?
- wordpress - 如何在functions.php中添加谷歌字体
- python - 如何让重复计算更有效率?功能建议?
- javascript - 如何使用 .fetch() 将参数传递给后端中的函数?ReactJS + 节点
- python-3.x - 匹配数据帧的记录多于计数
- android - 在 Android 上使用 Sharedpreferences 的存储问题
- php - While循环PHP内部的多个查询
- selenium - 用于自动化 Oracle ADF 登录的 Selenium Web 驱动程序