You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何实现React自定义Authorize组件控制子元素显隐?

Solution: Build a React Authorize Component for Conditional Rendering

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 23:37:51