简体   繁体   中英

Triggering a parent function from child using props

I am trying to do something simple: I want my child component to trigger a function found in my parent component, and I understand the right way is using props.

In the following Codepen you can find an example:

https://codepen.io/akmur/pen/MvXGEG

Basically what I want to achieve is to print "hey" to console.

This is my code:

class Form extends React.Component {
  constructor(props){
    super(props);
  }

  onClickAdd(){
    this.props.addItem();
  }

  render(){
    return(
      <div>
        <button onClick={this.onClickAdd}>Add</button>
      </div>
    )
  }
}

class App extends React.Component {
  constructor(props){
    super(props);
  }

  addItem(){
    console.log('hey');
  }

  render() {
    return (
      <div>
        <Form addItem={this.addItem} />
      </div>
    );
  }
}

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

Thanks for your help!

You don't need the onClickAdd function. Just call this.props.addItem directly onClick (notice, no parens) that you passed down.

 class Form extends React.Component {
  constructor(props){
    super(props);
  }

  render(){
    return(
      <div>
        <button onClick={this.props.addItem}>Add</button>
      </div>
    )
  }
}

class App extends React.Component {
  constructor(props){
    super(props);
  }

  addItem(){
    console.log('hey');
  }

  render() {
    return (
      <div>
        <Form addItem={this.addItem} />
      </div>
    );
  }
}

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

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