【发布时间】:2020-08-02 08:53:53
【问题描述】:
当我遇到一个通过子组件回调更新父组件的示例时,我正在经历 react official documentation。我能够理解流程是如何工作的。但是,当我尝试进一步优化代码时,它无法通过回调更新组件。
原始代码:
https://codepen.io/gaearon/pen/QKzAgB?editors=0010
我的代码更改:
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};
this.button = <MyButton message="Login" onClick={this.handleLoginClick} />;
}
handleLoginClick() {
this.setState({isLoggedIn: true});
}
handleLogoutClick() {
this.setState({isLoggedIn: false});
}
render() {
const isLoggedIn = this.state.isLoggedIn;
if (isLoggedIn) {
this.button = <MyButton message="Logout" onClick={this.handleLogoutClick} />;
} else {
this.button = <MyButton message="Login" onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{this.button}
</div>
);
}
}
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 />;
}
class MyButton extends React.Component {
constructor(props) {
super(props);
this.message=props.message;
this.click=props.onClick;
}
render() {
return (
<button onClick={this.click}>
{this.message}
</button>
);
}
}
ReactDOM.render(
<LoginControl />,
document.getElementById('root')
);
【问题讨论】:
-
codepen 链接似乎对我有用。你看到了什么错误?
-
代码正在运行...请包括您在问题中遇到的错误。
-
codeopen 链接正常工作。如果您剪切粘贴我的代码,然后尝试单击显示的按钮,它将不起作用。
标签: javascript reactjs jsx react-component