简体   繁体   English

从子组件更改父组件状态

[英]Change parent component state from child component

I know that the question with this title has already been asked few times before but the problem is that I couldn't get an appropriate answer. 我知道这个标题的问题已经被问过几次了,但是问题是我找不到合适的答案。 So as I am new to reactJS and trying to create login logout form. 因此,由于我是reactJS并尝试创建登录注销表单。

What I want to do is to pass or change a state of parent component from a child component through an event handler( When a user clicks on logout button ). 我要做的是通过事件处理程序( 当用户单击注销按钮时 )从子组件传递或更改父组件的状态。 Below are the two Components: 以下是两个组件:

First One: 第一:

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>
        );
    }
}

And Second: 其次:

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>
        );
    }
}

I have simplified these component to come on point. 我已经简化了这些组件以供参考。

What's going here? 这是怎么回事 Home Component is the main parent component. Home组件是主要的父组件。 Initially the state.login is false and in this situation LoginScreen Components shows up. 最初, state.loginfalse ,在这种情况下显示LoginScreen Components。 Now, when user login through LoginScreen Component state.login updates to true , it's time to show for ChatBox Component. 现在,当用户通过LoginScreen Component state.login登录更新为true ,该显示ChatBox Component了。

Now you can see that ChatBox Component contains a button which calls a method logout to logout user. 现在您可以看到ChatBox组件包含一个按钮,该按钮调用方法logout来注销用户。 What I want is to update once again the state.login to false in Home Component When user click on the Logout Button . 我想要的是当用户单击注销按钮时,将Home Component中的state.login再次更新为false

I don't know how to do it, It will be appreciate if you help me. 我不知道该怎么做,如果您能帮助我,将不胜感激。

Thanks in advance. 提前致谢。

Do it in the same way as you are doing for Login, pass a function as a prop and call it on logout, see updates below. 以与登录相同的方式进行操作,将功能作为道具传递,并在注销时调用它,请参见下面的更新。

 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> 

You can pass an event from the Parent component to the Child component that handles the change of the state, like so: 您可以将事件从Parent组件传递给处理状态更改的Child组件,如下所示:

class App extends React.Component {

  constructor() {
    super();
    this.state = { isLoggedIn: false };
  }

  _handleLogin() {
    this.setState({ isLoggedIn: true });
  }

  _handleLogout() {
    this.setState({ isLoggedIn: false });
  }

  render() {
    const { isLoggedIn } = this.state;

    return (
        <div>
       {
            isLoggedIn ?
            <ChatBox logoutEvent={this._handleLogout.bind(this)} />
          :
          <Login loginEvent={this._handleLogin.bind(this)} />
       }
        </div>
    );
  }
}

const Login = ({ loginEvent }) => (
    <button type="button" onClick={loginEvent}>Login</button>
);

const ChatBox = ({ logoutEvent }) => (
    <div>  
    <h1>This is the Chat Box!</h1>
    <button type="button" onClick={logoutEvent}>Logout</button>
  </div>
);

ReactDOM.render(
  <App />,
  document.getElementById('container')
);

Here's the fiddle 这是小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM