react条件渲染完整代码
时间: 2023-12-06 10:03:21 浏览: 141
react.js完整项目
4星 · 用户满意度95%
以下是React条件渲染的完整代码示例:
```jsx
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false
};
}
render() {
let isLoggedIn = this.state.isLoggedIn;
let button = null;
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
}
handleLoginClick = () => {
this.setState({ isLoggedIn: true });
}
handleLogoutClick = () => {
this.setState({ isLoggedIn: false });
}
}
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
function LoginButton(props) {
return (
<button onClick={props.onClick}>
Login
</button>
);
}
function LogoutButton(props) {
return (
<button onClick={props.onClick}>
Logout
</button>
);
}
export default App;
```
阅读全文