我知道这个标题的问题之前已经被问过几次了,但问题是我无法得到合适的答案。因此,因为我是 reactJS
的新手,并尝试创建登录注销表单。
我想要做的是通过事件处理程序从子组件传递或更改父组件的状态(当用户单击注销按钮时)。以下是两个组件:
第一个:
class Home extends React.Component {
constructor(props){
super(props);
this.state = {login : false};
}
login(){
// this method updates the login.state : true
}
render() {
return (
<div>
{this.state.login ? (<ChatBox userNick="fad" />) : (<LoginScreen onSubmit={this.login} />) }
</div>
);
}
}
第二:
class ChatBox extends React.Component{
logout(){
// Expecting or trying to update parent.state.login : false
// via this method as well
}
render() {
return (
<div className="chat-box">
<button onClick={this.logout} > Logout </button>
<h3>Hi, {this.props.userNick} </h3>
</div>
);
}
}
我已经简化了这些组件以使其正常工作。
这里发生了什么?
Home
组件是主要的父组件。最初,state.login
为 false
,在这种情况下,LoginScreen
组件会显示。现在,当用户通过 LoginScreen
组件登录 state.login
更新为 true
时,就可以显示 ChatBox
组件了.
现在您可以看到 ChatBox
组件包含一个按钮,该按钮调用方法 logout
来注销用户。 我想要是再次将 Home
组件中的 state.login
更新为 false
当用户单击注销按钮。
我不知道该怎么做,如果你能帮助我,我将不胜感激。
提前致谢。
最佳答案
按照与登录相同的方式进行操作,将函数作为 Prop 传递并在注销时调用它,请参阅下面的更新。
const LoginScreen = () => (<div>Login Screen</div>);
class Home extends React.Component {
constructor(props){
super(props);
this.state = {login : true};
this.logout = this.logout.bind(this);
}
login(){
// this method updates the login.state : true
}
logout() {
// this method updates the login.state : false
this.setState({ login: false });
}
render() {
return (
<div>
{this.state.login ? (<ChatBox userNick="fad" onLogout={this.logout} />) : (<LoginScreen onSubmit={this.login} />) }
</div>
);
}
}
class ChatBox extends React.Component{
constructor(props) {
super(props)
// This makes sure `this` keeps pointing on this instance when logout is called from the outside.
this.logout = this.logout.bind(this);
}
logout(){
// Call the onLogout property.
this.props.onLogout();
}
render() {
return (
<div className="chat-box">
<button onClick={this.logout} > Logout </button>
<h3>Hi, {this.props.userNick} </h3>
</div>
);
}
}
ReactDOM.render(<Home />, document.querySelector('#main'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="main"></div>
关于javascript - 从子组件更改父组件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44562884/