条件渲染示例
2025年11月29日
作者:管理员
示例代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>React 条件渲染</title>
<script crossorigin src="https://unpkg.com/react@18.3.1/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<style>
body { font-family: system-ui, sans-serif; padding: 20px; }
button { margin: 5px; padding: 8px 16px; font-size: 16px; }
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function LoginButton({ isLoggedIn }) {
if (isLoggedIn) {
return <button>退出登录</button>;
} else {
return <button>登录</button>;
}
}
function App() {
const [isLoggedIn, setIsLoggedIn] = React.useState(false);
return (
<div>
<LoginButton isLoggedIn={isLoggedIn} />
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
切换登录状态
</button>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
</script>
</body>
</html>