无法调用道具子功能

Can't call props child function

我想在按下按钮时调用父组件中的函数 子组件,

class Home extends Component {
  constructor(props) {
    super(props);
    this.Quiz = this.getQuizpopup.bind(this); //Function I want to call 

    this.state = {
      latitude: LATITUDE,
    }

  };
}

在子组件中,我使用如下方式调用函数

<View>
  <Button onPress={this.props.Quiz()} buttonStyle={styles.buttonStyle} title="MpTest" />
</View>

我得到的错误是

您需要传递道具才能在您的子组件中使用该功能。

class Parent extends Component{
quiz = () => {
  //function you want to call
}
render(){
return(
  <Child quiz={this.quiz}> //passing quiz function as prop to child component 
)
}}

您应该在 child 组件中传递一个 prop 作为回调,点击它可以触发 parent 中的函数调用。

您的代码应如下所示:

class Home extends Component {
   constructor(props) {
     super(props);
     this.Quiz = this.getQuizpopup.bind(this); //Function I want to call 
     this.state = {
      latitude: LATITUDE,
     }
  }

  Quiz = () => {
    //button click handler.
  }

  render () {
     return (
        <Child
           onQuizButtonClick = {this.Quiz} />
     ) 
  }
}

在您的 child 中,代码应该是:

  <Button onPress={() => this.props.onQuizButtonClick()} buttonStyle={styles.buttonStyle} title="MpTest" />