简体   繁体   English

React-在组件函数内部调用props函数

[英]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: 然后在我的子组件中,我想在另一个函数中调用该toggleDropdown函数,如下所示:

// 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? 我以为您可以执行类似的操作,但是看来您只能在元素上调用prop函数?

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 传递给子组件的prop被命名为toggle而不是toggleDropdown ,因此您需要像在removeItem组件中那样调用它

// 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 您可能需要做的其他事情是使用bindarrow functions绑定removeItem 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. 子组件的toggleDropdown命名为toggle ,而toggleDropdown属于父组件。

This should work in the child component: 这应该在子组件中起作用:

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

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

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