简体   繁体   中英

React - Call props function inside of a components function

Trying to do something like this:

// Component one

toggleDropdown() {
  setState({open: !open}
}

render () {
  return (
   ChildComponent toggle={this.toggleDropdown} />
  )
}

Then in my child component I'd like to call that toggleDropdown function in another function like this:

// This gets triggered on click.
removeItem() {
  // remove scripts then:
  this.props.toggleDropdown()
}

I thought you'd be able to do something like this but it appears that you can only call prop functions on the element?

The prop that you are passing down to the child component is named toggle and not toggleDropdown and hence you need to call it like that in the removeItem component

// This gets triggered on click.
removeItem() {
  this.props.toggle()
}

Other things that you might need to do is to bind your removeItem function using bind or arrow functions

constructor(props) {
    super(props);
    this.removeItem = this.removeItem.bind(this);
}

or

// This gets triggered on click.
removeItem = () => {
  this.props.toggle()
}

您只需要调用toggle而不是toggleDropdown

this.props.toggle();

The child component's prop is named toggle , while toggleDropdown belongs to the parent component.

This should work in the child component:

removeItem() {
    this.props.toggle();
}

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