簡體   English   中英

React Native-如何從子組件中調用函數?

[英]React Native - How to call a function from a child component?

我正在嘗試制作一個Timer組件,該組件應在從父組件調用其start函數時啟動:

計時器:

class Timer extends Component {
   start = () => {
      //starts the timer here
   }
}

家長:

class Parent extends Component {
   render () {
      <Timer /> // how do I call the start function from this parent component?
   }
}

您可以通過設置對子級的引用來從父級調用子級功能。

//Child
class Timer extends Component {
    start = () => {
        //starts the timer here
    }
}

//Parent
class Parent extends Component {

    rende() {
        <Timer ref={ ( component ) => this.Timer = component }/>
    }

   someParentFunction() {
       this.Timer.start();
   }

}

您應該從<Timer>觸發更改道具,然后在componentWillReceiveProps啟動計時器。 小例子

class Parent extends Component {
    //set the state to this.state={runTimerStart: false}
    onParentAction = () => {   //call this onParentAction function when you want to start the timer
        this.setState({runTimerStart: true})
    }
    render () {
        <Timer runStart={this.state.runTimerStart}/> 
    }
}

<Timer>

componentWillReceiveProps(nextProps){
  if(nextProps.runTimerStart === true){
    //Perform some operation, call your start function
  }
}

因此,以下做法確實是不好的做法,通常,如果您發現自己需要從孩子傳給父母的情況下,會遇到更大的問題。

同樣,不應逐字使用此解決方案,而應為您提供如何從子代將函數傳遞回父代的真正好主意

class Timer extends Component {
   componentDidMount() {
      this.props.setIt(this.start)
   }

   start = () => {
      //starts the timer here
   }
}

class Parent extends Component {

   setIt = (startTrigger) => {
     startTrigger() // You now have access to this function to do what you wish
   }

   render () {
      <Timer setStartTrigger={this.setIt} />
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM