自定义可重复使用的react组件,以基于标志显示或隐藏子元素



试图创建一个自定义组件来使用react显示或隐藏子元素,但没有得到任何关于我的需求的参考,最终以SO告终。我想创建一个简单的组件来显示或隐藏这些子元素,如下所示。

<Authorize isAuthorized={true} >
<div>
Welcome User
</div>
</Authorize>

所以您希望利用children道具:

const Authorize = props => {
if (props.isAuthorized) {
return props.children;
}
// Return non-authorized content/warning
return "You are not authorized";
}

现在,您可以随心所欲地使用组件:

<Authorize isAuthorized={true}>
<div>
Welcome User
</div>
</Authorize>

试试这个:

import React from 'react';
export const Authorized = ({isAuth, children}) => {
return isAuth ? <>{children}</>: <h1>not allowed...</h1>;
}

最新更新