我尝试将 react doc 代码重写为 react-create-app 中的类组件,但如果行为不正确



你好,我目前正在学习React,我正在本地React-create应用程序中重写文档中的所有代码示例。我在文档的这一部分遇到了问题,代码笔在这里:

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
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
{button}
</div>
);
}
}
function LoginButton(props) {
return (
<button onClick={props.onClick}>
Login
</button>
)
}
function LogoutButton(props) {
return (
<button onClick={props.onClick}>
Logout
</button>
)
}
ReactDOM.render(
<LoginControl />,
document.getElementById('root')
);

在这段代码中,我只是假设显示一个按钮,如果是this.state.isLoggedIn === true,则显示"登录",如果是false,则显示显示"注销"。这个代码运行得很好,它是来自Doc的代码。

我的问题:但是,当我在电脑上运行代码时(如下所示(,按钮只工作一次,然后没有其他任何东西附加任何状态更改,也没有调用生命周期函数。在这一点上,我不知道出了什么问题。

这是我的代码:

import React from 'react'
export default class LoginControl extends React.Component {
constructor(props) {
super(props);
this.state = {isLoggedIn: false}
this.handleLoginClick = this.handleLoginClick.bind(this)
this.handleLogoutClick = this.handleLogoutClick.bind(this)
}
handleLoginClick() {
this.setState({isLoggedIn: true})
}
handleLogoutClick() {
this.setState({isLoggedIn: false})
}
render() {
const isLoggedIn = this.state.isLoggedIn
let button
if (isLoggedIn) {
button = <LogoutButton onClik={this.handleLogoutClick}/>
} else {
button = <LoginButton onClick={this.handleLoginClick}/>
}
return (
<div>
{button}
</div>
)
}
}
function LoginButton(props) {
return (
<button onClick={props.onClick}>
Connect
</button>
)
}
function LogoutButton(props) {
return (
<button onClick={props.onClick}>
Disconnect
</button>
)
}

它在App.js中显示如下:

import React from "react";
import LoginControl from "./components/LoginControl";
export default class App extends React.Component {
render() {
return (
<div className={"container"}>
<LoginControl/>
</div>
)
}
}

和index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js'
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

我做错了什么?非常感谢。

您正在传递"onClik";prop到LogoutButton,而不是";单击";。请注意,缺少";c";

最新更新