求助:如何实现React自定义Authorize组件控制子元素显隐?
Hey there! Creating this Authorize component is super straightforward with React's built-in conditional rendering. Let's walk through a couple of implementations to match your needs.
Basic Implementation
This version will render your child content only when isAuthorized is true, and return null (nothing) when it's false:
import React from 'react'; const Authorize = ({ isAuthorized, children }) => { // Simple conditional: show children if authorized, else hide return isAuthorized ? children : null; }; export default Authorize;
How to Use It
Just like you wanted:
<Authorize isAuthorized={true}> <div>Welcome User</div> </Authorize>
Extended Version with Fallback Content
If you want to show a custom message when the user isn't authorized, add a fallback prop:
import React from 'react'; const Authorize = ({ isAuthorized, children, fallback = null }) => { // Show children if authorized, else show fallback content return isAuthorized ? children : fallback; }; export default Authorize;
Usage with Fallback
<Authorize isAuthorized={false} fallback={<div>Oops! You don't have permission to view this.</div>} > <div>Welcome User</div> </Authorize>
Add Type Safety (Optional)
To make your component more robust, add type checking with PropTypes or TypeScript.
Using PropTypes:
import PropTypes from 'prop-types'; // Add this after your component definition Authorize.propTypes = { isAuthorized: PropTypes.bool.isRequired, children: PropTypes.node, fallback: PropTypes.node };
Using TypeScript:
import React from 'react'; type AuthorizeProps = { isAuthorized: boolean; children: React.ReactNode; fallback?: React.ReactNode; }; const Authorize = ({ isAuthorized, children, fallback = null }: AuthorizeProps) => { return isAuthorized ? children : fallback; }; export default Authorize;
That's all! This component is flexible, reusable, and exactly matches the syntax you were aiming for. You can drop it into your React app and start using it right away.
内容的提问来源于stack exchange,提问作者Mohankumar Rathinam

