试图创建一个自定义组件来使用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>;
}