简体   繁体   中英

Is a function passed as props in this code?

I am new to React and came across this React code:

class Dashboard extends React.Component {
  state = { username: '' };

  render() {
    return (
      <div>
        <WelcomeMessage username={this.state.username} />
        <SettingsForm
          username={this.state.username}
          updateUsername={newUsername => {
            this.setState({ username: newUsername });
          }}
        />
      </div>
    );
  }
}

The question is what is this code about:

updateUsername={newUsername => {
            this.setState({ username: newUsername });
          }}

Is a function passed as props???

Yes, a function is passed as props in the Dashboard component.

By passing:

updateUsername={newUsername => {
  this.setState({ username: newUsername });
}}

the child component can call updateUsername(_myNewUserName_) which will set the state in its parent component.

It may be beneficial to take a look at event bubbling to see this concept in action.

Hope this helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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