我正在学习React JS并尝试根据登录状态实现基本登录按钮和文本,按钮文本正在更改但欢迎文本未被更改(这是从另一个文件导入)。请参阅下面的代码。
import React from 'react';
import Greeting from './Greeting';
function LoginButton(props) {
return <button onClick={props.onClick}>Login</button>;
}
function LogoutButton(props) {
return <button onClick={props.onClick}>Logout</button>;
}
class LoginControl extends React.Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = {isLoggedIn: false};
}
handleLoginClick() {
this.setState({isLoggedIn: true});
}
handleLogoutClick() {
this.setState({isLoggedIn: false});
}
render() {
const 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>
);
}
}
export default LoginControl;
import React, { Component } from 'react';
function UserGreeting() {
return <h1>Welcome back!</h1>;
}
function GuestGreeting() {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedin;
if(isLoggedIn) {
return <UserGreeting />;
} else {
return <GuestGreeting />;
}
}
export default Greeting;
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import LoginControl from './LoginControl';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<section>
<LoginControl />
</section>
</div>
);
}
}
export default App;
这是否发生是因为我在两个文件中使用相同的const isLoggedIn
答案 0 :(得分:1)
改变这一点。它的工作原理
function Greeting(props) {
const {isLoggedIn} = props;
if(isLoggedIn) {
return <UserGreeting />;
} else {
return <GuestGreeting />;
}
}