![](/img/trans.png)
[英]Imported components transformed into "/static" urls in react-create-app
[英]I try to rewrite react doc code as class components in a react-create-app but if doesn't behave properly
您好,我目前正在嘗試學習 React,並且我正在重寫本地 react-create-app 中文檔中的所有代碼示例。 我在文檔的這一部分遇到了麻煩,請在此處使用 codepen :
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
和 'Logout' 如果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”道具傳遞給LogoutButton而不是“onClick”。 請注意缺少“c”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.